Talking about ASP.NET Core 2.0 Middleware

Time:2020-11-26

problem

How to create the simplest ASP.NET Core middleware?

answer

Use VS to create a ASP.NET Empty project of core 2.0, please note Startup.cs Configure() method in:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.Run(async (context) =>
  {
    await context.Response.WriteAsync("Hello World! (Run)");
  });
}

A better way to create a request pipeline is to use the extension method on iaapplicationbuilder


public static void RunHelloWorld(this IApplicationBuilder app)
{
  app.Run(async (context) =>
  {
    await context.Response.WriteAsync("Hello World! (Run)");
  });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.RunHelloWorld();
}

Run, the page displays:

We use it above IApplicationBuilder.Run () to configure middleware. Another method is IApplicationBuilder.Use ():


public static void UseHelloWorld(this IApplicationBuilder app)
{
  app.Use(async (context, next) =>
  {
    await context.Response.WriteAsync("Hello World! (Use)\n");
    await next();
  });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.UseHelloWorld();
  app.RunHelloWorld();
}

Run, the page displays:

It is better to define middleware as a separate class


public class HelloWorldMiddleware
{
  private readonly RequestDelegate _next;

  public HelloWorldMiddleware(RequestDelegate next)
  {
    _next = next;
  }

  public async Task Invoke(HttpContext context)
  {
    await context.Response.WriteAsync("Hello World! (Use in Class)\n");
    await _next(context);
  }
}


public static class UseHelloWorldInClassExtensions
{
  public static IApplicationBuilder UseHelloWorldInClass(this IApplicationBuilder app)
  {
    return app.UseMiddleware<HelloWorldMiddleware>();
  }
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.UseHelloWorld();
  app.UseHelloWorldInClass();
  app.RunHelloWorld();
}

Run, the page displays:

discuss

Middleware is a component that intercepts HTTP request and response messages. We create a request pipeline for our application by creating these component chains.

We use the iaapplicationbuilder parameter of the configure() method to create the request pipeline. The iaapplicationbuilder parameter has the following methods:

  1. Run (): adds middleware and terminates the request pipeline (that is, the next middleware is no longer called).
  2. Use (): add middleware, use lambda expression or a concrete class.
  3. Map (): add middleware according to the request path.

Run

This method takes the requestdelegate delegate as a parameter and the httpcontext parameter when the delegate method is called. This delegate method returns void because it terminates the request pipeline.

Use

This method takes the func delegate as a parameter. The delegate method has two parameters, httpcontext and the next pointing to the next middleware, and returns null. If the next middleware is not called, the request pipeline is terminated (the same as run).

UserMiddleware

When creating middleware through a separate class, we use the usemiddleware method and use the specific implementation type as a generic parameter.

In the middleware class, there are two important parts:

1. The constructor accepts requestdelegate. When this delegate is called, the current request is passed to the next middleware.

2. It has an invoke method that receives the httpcontext parameter and returns null (task). When middleware is needed, the framework will actively call this method.

Note: it is best practice to implement Middleware in a separate class and encapsulate it with usemiddleware.

Extension method

Pay attention to the difference between extension methods. Runxxx does not return a value, while usexxx returns a value (iaapplication builder). This is because run() terminates the request pipeline and use() may link to other middleware.

order

The middleware is called in the order in which they appear in the configure() method. The response back to the client goes through the same middleware pipeline.

Source code download

Original text: https://tahirnaushad.com/2017/08/14/asp-net-core-middleware/

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.