Explanation of ASP.NET Core Middleware (middleware)

First, what is the middleware

Middleware is aggregated to the application to a processing request and response pipeline software. Each component:

  • You can choose whether the request should be passed to the next component in the pipeline.
  • And related business may be performed after the operation before the next call request pipeline assembly.

Second, the use of middleware to create a pipeline IApplicationBuilder

ASP.NET Core request pipeline and entrusted by a series of requests, the requests sequentially one by one delegate is invoked, the sequence shown in FIG composition (performed in the order of black arrows):

Microsoft officials example of FIG.

 

Each delegate may be performed before and after the next commission related operations. It may also decide not to delegate the request to the next delegate trust chain (we call a short circuit).

Short circuit is normally required, because it avoids unnecessary work.

For example: static file middleware returns the remainder of the request and the short duct static files.

          Exception processing request should be called early in the pipeline, so that they can capture request pipeline exception occurs in a subsequent stage.

The easiest ASP.NET Core applications a single set of requests to process all requests delegate. It does not include the actual request pipeline in this case. Instead, a single anonymous function called in response to each HTTP request.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

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

Second, the order

二、Use, Run, and Map

三、Use,Run and Map

Fourth, the built-in middleware

Fifth, custom middleware

Typically, the middleware is encapsulated in a class, and by extension the disclosed method. The following middleware, it is provided according to the current request culture query string:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Use((context, next) =>
        {
            var cultureQuery = context.Request.Query["culture"];
            if (!string.IsNullOrWhiteSpace(cultureQuery))
            {
                var culture = new CultureInfo(cultureQuery);

                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;
            }

            //Next the delegate The Call / Middleware The Pipeline in 
// the calling application next delegate pipe / intermediate
return Next (); }); app.run ( the async (context) => { the await context.Response.WriteAsync ( $ " {} CultureInfo.CurrentCulture.DisplayName hello " ); }); } }

 

The test middleware http://localhost:7997/?culture=no.

The following code is moved to a middleware delegate class:

using Microsoft.AspNetCore.Http;
using System.Globalization;
using System.Threading.Tasks;

namespace Culture
{
    public class RequestCultureMiddleware
    {
        private readonly RequestDelegate _next;

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

        public Task Invoke(HttpContext context)
        {
            var cultureQuery = context.Request.Query["culture"];
            if (!string.IsNullOrWhiteSpace(cultureQuery))
            {
                var culture = new CultureInfo(cultureQuery);

                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;

            }

            // Call the next delegate/middleware in the pipeline
            return this._next(context);
        }
    }
}

By extension method IApplicationBuilder disclosed middleware

using Microsoft.AspNetCore.Builder;

namespace Culture
{
    public static class RequestCultureMiddlewareExtensions
    {
        public static IApplicationBuilder UseRequestCulture(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestCultureMiddleware>();
        }
    }
}

 

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseRequestCulture();

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync(
                $"Hello {CultureInfo.CurrentCulture.DisplayName}");
        });

    }
}

Middleware components can achieve the purpose of injection by inversion of control dependence constructor arguments. UseMiddleware<T>You can also directly accept other parameters.

to sum up

This paper describes the process of building ASP.NET Core request pipeline, as well as some help us be more convenient method to configure the extension request pipeline. In ASP.NET Core, at least have a middleware to respond to the request, and our application is actually just a collection of middleware, MVC is just one of the middleware only. Briefly, the middleware processing component is a http request and response, constitute a plurality of intermediate request processing pipeline, each intermediate can choose to end the processing, or passed on to the next intermediate duct, thus request pipeline formed in series. Typically, each middleware registered with us, every request and response will be called, but can also use the  Map ,  MapWhen , UseWhen and other extension methods for filtering middleware.

Guess you like

Origin www.cnblogs.com/weiwei858/p/7871664.html