ASP.NET Core Middleware With Examples

In ASP.NET Core, middleware is a component that can be plugged into the request processing pipeline to perform some action for each request. It sits between the server and the application and is responsible for handling requests and responses.

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.

Middleware can be thought of as a series of “pipes” through which a request flows, with each piece of middleware performing some action on the request and then passing it along to the next piece of middleware in the pipeline. This allows developers to modify the request and response objects at various points in the pipeline to add custom behavior to the application.

Usually, an application may contain multiple middleware components that can perform the following tasks:

  • In ASP.NET Core, middleware determines whether or not the HTTP request should be forwarded to the next component in the pipeline by calling the next() method.
  • Middleware processes incoming or outgoing HTTP requests or responses, modifies them as needed, and then either passes them on to other middleware or the ASP.NET Core web server.
  • We can have multiple middleware components in an ASP.NET Core application, each with a specific function such as authenticating users, handling exceptions, routing requests, and serving static files like JavaScript, CSS, and images. These middleware components work together to process incoming requests and produce appropriate responses.
  • HTTP requests in the middleware pipeline are managed by Request Delegates, which can be configured using the Use, Run, and Map extension methods.
Middleware MethodsDescription
Use:Adds a middleware delegate defined in-line to the application’s request pipeline. It allows passing the HTTP request to the next middleware within the pipeline.
Map:Branches 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.
Run:Adds 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 pipeline 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, the Configure method is a method in the Startup class that is used to configure the request processing pipeline for an application. It is called by the host when the application starts up and is passed an IApplicationBuilder object and an IWebHostEnvironment object as arguments.

The Configure method is where you can add middleware to the request processing pipeline and configure other aspects of the application, such as routing, dependency injection, authentication, and other hosting options.

  • The Configure method is an important part of the ASP.NET Core request processing pipeline and is where you can add and configure middleware and other application components.
  • The Configure method in ASP.NET Core uses the IApplicationBuilder instance to handle all HTTP requests. You can register multiple middleware components in the Configure method, but the order in which they are registered is important as it determines the order in which they will be executed for each request.
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 has been used to redirect 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 the session state.
UseEndpoints:Endpoint Routing Middleware with MapRazorPages to add Razor Page’s endpoints to the request pipeline.
ASP.NET Core middleware

Use() method in Middleware

In ASP.NET Core, the Use method is used to add middleware to the request processing pipeline. It is called on the IApplicationBuilder object and takes a middleware delegate as an argument. The middleware delegate is a function that receives an HttpContext object as an argument and returns a Task.

Example:

Here’s an example of how you might use the Use method to add multiple middlewares to the pipeline:

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 middlewares in the ASP.NET Core

In the above example, the Use method is being used to add a piece of middleware to the pipeline that will be executed for every request. The middleware delegate is passed an HttpContext object, which represents the current request and response, and a next delegate, which can be used to pass the request on to the next piece of middleware in the pipeline.

The Use method can be called multiple times to add multiple pieces of middleware to the pipeline. The middleware will be executed in the order it was added to the pipeline.

It’s important to note that the Use method is non-terminating, meaning that it will not short-circuit the request pipeline. This means that after the middleware delegate has been executed, the request will be passed on to the next piece of middleware in the pipeline unless the response has already been completed.

Run() method in Middleware

In ASP.NET Core, the Run method is used to add middleware to the request processing pipeline that will terminate the request pipeline. It is called on the IApplicationBuilder object and takes a middleware delegate as an argument. The middleware delegate is a function that receives an HttpContext object as an argument and returns a Task.

The Run method is terminating, meaning that it will short-circuit the request pipeline and prevent any further middleware from being executed. This is useful when you want to handle a request and immediately complete the response, without allowing any further middleware to modify the request or response.

It’s important to note that the Run method should generally be placed at the end of the middleware pipeline, as it will terminate the pipeline and prevent any further middleware from being executed.

Example:

Following is an example of how you might use the Run method to add middleware to the pipeline:

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 request processing pipeline will be terminated after that, so the request will never reach the second Run method.

Map() method in Middleware

In ASP.NET Core, the Map method is used to add middleware to the request processing pipeline that will only be executed for requests that match a specified pattern. It is called on the IApplicationBuilder object and takes a request path pattern and a middleware delegate as arguments. The middleware delegate is a function that receives an IApplicationBuilder object as an argument and returns void.

The Map method is useful when you want to add middleware that should only be executed for requests that match a specific pattern. It allows you to create separate branches in the request processing pipeline for different request paths.

The Map method in ASP.NET Core is used to match request delegates to requests based on the request’s path. It allows you to create branches in the request processing pipeline based on the request path. If the request path starts with the specified URL path, the corresponding branch of middleware will be executed.

Example:

Following is an example of how we can use the Map method to add middleware to the pipeline:

 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
Map extension method in ASP .NET Core

What is a Request delegate in ASP.NET Core?

In ASP.NET Core, a request delegate is a function that handles an incoming HTTP request and produces a response. It is passed an HttpContext object as an argument, which represents the current request and response, and returns a Task.

Request delegates are used to define the behavior of middleware in the request processing pipeline. They are typically passed to the Use, Run, or Map extension methods on the IApplicationBuilder object to add middleware to the pipeline.

Example:

Following is an example of a simple request delegate:

public async Task MyCustomMiddleware(HttpContext context)
{
    // Do something with the request and response
    await context.Response.WriteAsync("Hello, World!");
}

In the above code example, the request delegate MyCustomMiddleware is a simple function that writes “Hello, World!” to the response. It can be added to the request processing pipeline by calling the Use or Run extension method on the IApplicationBuilder object and passing the delegate as an argument.

Request delegates are an important part of the ASP.NET Core request processing pipeline and allow developers to add custom behavior to their applications.

References: MSDN ASP.NET Core Middleware

FAQ

Here are some common questions and answers about ASP.NET Core middleware:

Q: What is the purpose of the Configure method in the Startup class?

Ans: The Configure method in the Startup class determines how the application will handle each HTTP request as it moves through the request processing pipeline.
This is where you can add and configure multiple middleware components to meet your specific needs.
The Configure method takes an IApplicationBuilder interface as the first parameter and has two optional parameters: IHostingEnvironment and ILoggerFactory.
These parameters can be used to access information about the hosting environment and configure logging for the application.

Q: What is the Map method in ASP.NET Core middleware used for?

Ans: The Map method is used to add middleware to the request processing pipeline that will only be executed for requests that match a specified pattern. It allows you to create separate branches in the pipeline for different request paths.

Q: What is a Request delegate?

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

Q: What is middleware C#?

Ans: In ASP.NET Core, Middleware is the C# class that can handle an HTTP request or response.

Q: What is the difference between the Use and Run methods in ASP.NET Core middleware?

Ans: The Use method is used to add non-terminating middleware to the request processing pipeline, while the Run method is used to add terminating middleware.

Non-terminating middleware will pass the request on to the next piece of middleware in the pipeline after it has been executed unless the response has already been completed.
Terminating middleware, on the other hand, will short-circuit the request pipeline and prevent any further middleware from being executed.

Q: Can I use multiple middleware components in an ASP.NET Core application?

Ans: Yes, you can use multiple middleware components in an ASP.NET Core application. The order in which they are added to the request processing pipeline is important, as it determines the order in which they will be executed for each request.

Q: What are some common uses of middleware in ASP.NET Core?

Ans: Some common uses of middleware in ASP.NET Core include logging, exception handling, routing, authentication, authorization, and serving static files.

Middleware can be used to perform a wide range of tasks and can be customized to meet the specific needs of an application.

If you enjoyed reading this blog, please consider liking, commenting on, and sharing it with others.

Articles to Check Out:

Shekh Ali
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments