Want an absolute control over the request/response action of your application?

Middleware- the catalyst behind the soaring popularity of ASP.NET Core, can help you with this, allowing you to control each request and response activity of your application and making the software architecture comprehensible and meaningful.

So, what exactly is the Middleware?

Middleware, also termed as a software glue, is computer software that allows the applications/software to interact with the database, servers, remote systems, etc, depending on the type used. Middleware makes the communication within the application easier, controlling the HTTP requests and responses.

Before its introduction, the request and response objects in the ASP.NET projects, used to be very big as well as extremely tightly coupled with the web server software i.e.  Internet Information Services(IIS), making the objects difficult to handle. To solve this ASP.NET Core Middleware came into the picture, which showed the way to remove the dependency of the web applications on the server.

How does Middleware Works?

To use the middleware in the application, you need to build the request pipeline using the request delegates, which handles the HTTP request. You can configure the request delegates through the ‘Run’, ‘Map’, and ‘Use’ method on IApplicationBuilder.

These delegates decide whether the request should be passed to the next component in the application pipeline or not. Along with this, it can also perform the required actions such as saving data, before and after the invocation of the next component in the application pipeline. Then the response comes back in the same fashion through the pipeline.

  • Run method

    The Run method is an extension method that handles the requests, accepting the RequestDelegate parameter. The Run() method should be placed at the end of the pipeline as the method terminates the chain, preventing any other middleware to execute.

    app.Run(async context =>
    {
    await context.Response.WriteAsync("Hello from " + _environment);
    });
  • Use method

    The Use() method enables you to perform the action before and after the next middleware delegate. You can also call the required middleware delegate using the function next.Invoke(). It helps include the short-circuiting in the pipeline – a process in which the middleware, instead of passing a task to another middleware, executes it.

    app.Use(async (context, next) =>
    {
    await context.Response.WriteAsync("Hello from " + _environment);
    ...
    await next.Invoke(); // invoking the next middleware
    });
  • Map method

    The Map() method checks the path requested by the user and matches it with the path present in the parameter, finding the match the method runs the middleware. It also creates multiple paths and hence the terminating ends for the pipeline.

    How does Middleware Works

You can use multiple Middleware in the ASP.NET Core based web application as per the requirement, some are inbuilt within the frameworks and some of them you need to add through NuGet.

ASP. NET provides following built-in middleware components:

Middleware Description
Authentication Provides support for authentication in website and application
Session Provides support for user sessions management.
Routing Provides support for requested routes.
CORS Provides Cross-Origin Resource Sharing configuration.
Static Files Provides support for fetching and retrieving static files

How to set up a Middleware Pipeline in your Website?

Let’s say you want to set up the middleware pipeline in a website template. To do so, you need to use the Configure () method in the Startup class, which adds the following components:

  1. Error handling
  2. Static file server
  3. Cookie Policy
  4. MVC(with the area defined)
  5. Session
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Error Handling Middleware defined in Startup.cs
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
//app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
//For: Session
//The order of middleware is important. In the preceding example, an InvalidOperationException exception occurs when UseSession is invoked after UseMvc.
app.UseSession();
app.UseMvc(routes =>
{
// Add area
routes.MapRoute(
name: "Area",
template: "{addname?}/{area:exists}/{controller=Login}/{action=Index}/{id?}");
});
}

The order of the Middleware is very important, requiring you to strictly follow it in your website Here in this example, the first middleware that we have used is for error handling in both development and non-development environments.

In the case of the development environment, the UseDeveloperExceptionPage component is used, which adds the middleware to the pipeline. This middleware helps the developer to trace the errors and exceptions in the development phase.

For the non-developer environment, we are using the UseExceptionHandler middleware. This middleware collects the URL, places a request for it in the request pipeline as well as catches the exception that occurs in the calls.

UseHttpsRedirection Middleware directly redirects the HTTP request to the HTTPS.

UseStaticFiles Middleware serves the static files to be served by adding them to the pipeline. You can store the static file in the webroot and access it through the path. This module does not provide authorization checks to the files, however, if you wish to do the authorization check, you can store the files in any directory outside the webroot, reachable to the middleware.

UseCookiePolicy adds the CookiePolicyMiddleware handler to the specified request pipeline, which assures that the application abides the General Data Protection Regulation (GDPR) regulations.

UseSession is a method that provides support for user sessions management, enabling you to access and manage the session when called. If you don’t call this method, you won’t be able to access the sessions.

UseMvc is always used at the end when all the authentication and session handling is done. The UseMvc method adds the MVC to the request pipeline as well as enables attribute routing.

Conclusion

Component reusability has been one of the major goals of the software developers, bringing into picture numerous technologies and concepts like Storybook, distributed systems with centralized control, instead of placing a separate copy of the resource at each module.

Middleware also works on a similar idea, liberating the developers to execute some essential piece of code at every numerous stage, affecting the speed and performance of the application/website. Rather, it allows you to include the middlewares explicitly in the Startup file, which only needs to be executed once, giving you access to the other middlewares. You can use various middlewares as per the requirement of your website/application or even create a customized one of yours.

Middleware is one of the major reasons behind the success of ASP.NET core, providing numerous advantages to the developers, such as – real-time information flow, linear development process, information integrity, more control over the HTTP request/response, and improved software architecture.

ASP.NET Core Middleware is a simple yet powerful tool. To leverage it on your website and application, Hire a .NET Developer, who will not only create an outstanding website but also help you to achieve your unique project requirements.

ASP.NET Core Middleware_cta