HOMEAUTHORSBUSINESS
ASP.NET Core - Middleware

ASP.NET Core - Middleware

By Nisar
Published in ASP.NET
August 12, 2021
2 min read

In ASP.NET’s classic architecture, HttpHandlers and HttpModules took place in different phases of the request pipeline. Middleware is comparable to HttpHandlers and HttpModules, in that both need to be configured and executed with every request.

ASP.NET Core introduced a new concept called “middleware,” which executes on every request in an ASP.NET Core application.

Typically, ASP.NET Core web applications have a number of middleware activators. This can be pre-built framework provided you add via NuGet packages. If you need to change the order in which middleware runs, just be sure to insert it before or after the other one. A middleware adds or modifies HTTP requests and optionally passes control to the next component. The following figure illustrates what happens when a request goes through middleware components.

Configure Middleware

We can configure middleware in Startup’s Configure method using an IApplicationBuilder instance. The following example adds a single middleware to the pipeline using the Run() method, and passes “Hello World!” through it on each request that comes in.

public class Startup
{
  public Startup()
  {

  }

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  {
    //configure middleware using IApplicationBuilder here..
    app.Run(async (context) =>
    {
      await context.Response.WriteAsync("Hello World!");
    });
  }
}

The above example demonstrates how to use an extension method on IApplicationBuilder to add a piece of middleware that reports “Hello World!” when the request comes through.

Set up multiple middleware

Typically, most ASP.NET Core applications will have multiple middleware components that are executed sequentially due to the nature of the MVC architectural design pattern. The Run method configures a middleware so that it cannot call the next middleware, since if is configured as the last. The following code will only execute the first Run method and never reach the second Run method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.Run(async (context) =>
  {
    await context.Response.WriteAsync("Hello World From 1st Middleware");
  });
  // the following will never be executed
  app.Run(async (context) =>
  {
    await context.Response.WriteAsync("Hello World From 2nd Middleware");
  });
}

To use multiple middleware, call the Use() extension method. It is similar to the Run() method, but includes a next parameter so that it can invoke the next out of sequence middleware in the sequence. Consider this example:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.Use(async (context, next) =>
  {
    await context.Response.WriteAsync("Hello World From 1st Middleware!");
    await next();
  });

  app.Run(async (context) =>
  {
    await context.Response.WriteAsync("Hello World From 2nd Middleware");
  });
}

The preceding example will show. Hello World From 1st Middleware!Hello World From 2nd Middleware! in the browser.

Thus, we can use the Use() method to configure multiple middlewares in any order.

Some Built-in Middleware

ASP.NET Core is a modular framework, which can be used to add server-side features in our application by installing them via NuGet. The following middleware are built-in:

Authentication: Enables authentication.

CORS: Sets cross-origin resource sharing.

Routing: Adds routing capabilities to the MVC framework.

Session: Adds support for user session.

StaticFiles: Adds support for serving and browsing files.

Diagnostics: The Error Handling add-in support for error reporting and handling.

Conclusion

ASP.NET Core has revolutionized the web application landscape by introducing the middleware concept, a modular and extensible approach to handle HTTP requests in the pipeline. Middleware serves as the backbone for processing requests and responses, replacing the older mechanisms of HttpHandlers and HttpModules. With the flexibility to arrange them in any desired order, developers can easily manipulate the flow of data and the behavior of their applications. By leveraging built-in middleware components like Authentication, CORS, Routing, and others, one can enhance their web applications without the need to reinvent the wheel. As we embrace this new paradigm, it’s essential to understand the nuances of configuring middleware to ensure optimal performance and functionality of our ASP.NET Core applications.


Nisar

Nisar

Product Designer

Sed commodo, est quis maximus fermentum, massa ipsum euismod neque, in varius risus tellus quis lacus. Sed ac bibendum odio.

Expertise

Product research
DotNET
NodeJS
React
Angular

Social Media

website

Related Posts

GRPC With ASP.NET Core
ASP.NET
GRPC With ASP.NET Core
September 05, 2023
1 min
© 2023, All Rights Reserved.

Quick Links

About UsContact Us

Social Media