ASP.NET Core Middleware With Examples

asp-net-core-middleware
asp-net-core-middleware

What is the middleware in ASP.NET Core?

In ASP.NET Core, middleware is a piece of code that is assembled into an application pipeline to handle HTTP requests and responses.
Usually, an application may contain multiple middleware components that can perform the following tasks:

    • Determines if the HTTP Request should be passed to the next component in the pipeline. This is accomplished by using the next() method in the middleware.
    • Process an incoming or outgoing HTTP request or response, modify it, and pass it to other middleware or the ASP.NET Core web server.
    • We might have a middleware component that authenticates a user, another middleware component that handles exceptions, yet another middleware component that routes requests, and yet another middleware component that serves static files like JavaScript files, CSS files, and pictures, among other things.

The HTTP requests in the middleware pipeline are managed by Request Delegates which can be configured using the  Use ,  Run , and  Map extension methods.

MethodDescription
UseAdds a middleware delegate defined in-line to the application’s request pipeline. It allow to pass the HTTP request to the next middleware within the pipeline.
MapBranches the request pipeline based on matches of the given request path. If the request path starts with the given URL path, the branch is executed.
RunAdds a terminal middleware delegate to the application’s request pipeline. This will be used to end the pipeline registrations and acts as a final step. In simpler words, this should be used at the very last step of the pipelines when you want to start the actual application.
ASP.NET Core Use, Map, and Run extension methods.

Middleware Ordering in ASP.NET Core

In an ASP.NET Core web application, the correct sequence of middleware layers is represented in the diagram below. It is important to add the middleware in the correct sequence, or the application may not work as planned. It’s crucial to know where each request delegate belongs in the pipeline.

Middleware Ordering in ASP.NET Core
Middleware Ordering in ASP.NET Core

Configure Middleware

In ASP .NET Core application, middlewares are registered in the  Startup.cs  file. All HTTP requests are handled by the Configure method using IApplicationBuilder instance. You can register as many middlewares as you want, but the order in which they are registered is important.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseRouting();
    app.UseCors();

    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();
    app.UseResponseCaching();

    // Custom middleware components
	// app.UseMiddleware<MiddlewareName>(); 

    app.UseEndpoints(endpoints =>    
    {    
      //  endpoints.MapRazorPages();  
            endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");                
    }); 
}
MiddlewareDescription
Exception:The Exception middleware is used to report application runtime errors when the application is run in the Development or Production environments.
UseHttpsRedirection:HTTPS Redirection Middleware is used to redirects HTTP requests to HTTPS.
UseStaticFiles:Static File Middleware returns static files (ex. JavaScript files, CSS files, and pictures) and short-circuits further request processing.
UseCookiePolicy:Adds the CookiePolicyMiddleware handler to the specified IApplicationBuilder, which enables cookie policy capabilities & display (GDPR) regulations messages.
UseRouting:Routing Middleware is used to route HTTP requests.
UseAuthentication:Authentication Middleware attempts to authenticate the user before they’re allowed access to secure resources.
UseAuthorization:Authorization Middleware authorizes a user to access secure resources.
UseSession:Session Middleware establishes and maintains session state.
UseEndpoints:Endpoint Routing Middleware with MapRazorPages to add Razor Pages endpoints to the request pipeline.
ASP.NET Core middleware

app.Use method

The  app.Use  extension method allow us to configure multiple middleware in the pipeline. first declaration parameter(context) will execute the response line and then the next parameter (next) passes the execution to the next middleware using next() method.
Let’s consider the following example with the app.Use extension method to configure multiple middleware in asp .net core.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async (context, next) =>
            {
               await context.Response.WriteAsync("Middleware 1 \n");
                await next();
            });
            app.Use(async (context, next) =>
            {
              await  context.Response.WriteAsync("Middleware 2");
                await next();
            });
        }
app.Use multiple middlewares in aspnet core
app.Use : configure multiple middleware in asp .net core

app.Run() method

The Run() method is an extension method on the IApplicationBuilder Interface that accepts a parameter of RequestDelegate type to handles the HTTP request. The Run() method enables short-circuiting with a terminal middleware delegate and is added at the end of the request pipeline because it cannot call the next middleware in the pipeline.

The  app.Run  extension method is used to end up the request pipeline registrations, as seen below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async (context, next) =>
            {
               await context.Response.WriteAsync("Middleware 1 \n");
                await next();
            });
            app.Use(async (context, next) =>
            {
              await  context.Response.WriteAsync("Middleware 2 \n");
                await next();
            });

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Middleware 3 \n");
            });

            // The below middleware will never execute as we already used app.Run()
            // method in the above statement.
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Middleware 4 \n");
            });
        }
app.Run middleware in aspnet core
app.Run extension method

In the example above, only the first Run() method will be called, and the pipeline will be terminated after that; the request will never reach the second Run() method.

app.Map() method

The app.Map() method is used to match request delegates based on matches of the given request’s path. This method allows branching of the pipeline path. If the request path starts with the given URL path, the branch is executed.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use(async (context, next) =>
            {
               await context.Response.WriteAsync("Middleware 1 \n");
                await next();
            });

            app.Map("/Map1", HandleMapRequest);

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Middleware 3 \n");
            });          

        }
        private static void HandleMapRequest(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                await context.Response.WriteAsync(" Middleware 2 from app.Map() \n");
            });
        }
app.Map method in aspnet core
app.Map extension method

References: MSDN ASP.NET Core Middleware

FAQ’s

Q: What is the use of the Configure method of startup class?

Ans: The Configure method in the startup class defines how the application will respond to each HTTP request in the application request pipeline. This is the place where you can configure multiple middleware to meet your specific requirements. It accepts the IApplicationBuilder interface as the first parameter and also it has two optional parameters called IHostingEnvironment and ILoggerFactory.

Q: What is the purpose of the Map extension method when adding middleware to the ASP.NET Core pipeline?

Ans: The app.Map() extension method is used to match request delegates based on the given request path.

Q: What is Request delegate in ASP.NET Core?

Ans: Request delegates are used to build request pipelines and handle each HTTP request. It is use to configure the Run, Map, and Use extension methods.

Q: What is middleware C#?

Ans: ASP.NET Core middleware are the C# classes that can handle an HTTP request or response.

Thank you for reading the blog. if you enjoyed it, please like, comment, and share it with others.

Articles to Check Out

Leave a Comment