Asp.Net Core学习笔记5——中间件

Asp.Net Core学习笔记5——中间件

1.中间件

中间件是组装到应用程序管道中以处理请求和响应的软件 。用户每一次请求都会被放到一个请求管道,这个请求管道通过动态配置各种业务逻辑对应的中间件,从而应对不同用户做出不同的请求响应

 

2.中间件管道的处理流程

 

下面是一个简单的中间件例子:

 

            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("First Middleware in. \r\n");
                await next.Invoke();
                await context.Response.WriteAsync("First Middleware out. \r\n");
            });

            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Second Middleware in. \r\n");
                // 水管阻塞,封包不往后送
                var condition = false;
                if (condition)
                {
                    await next.Invoke();
                }
                await context.Response.WriteAsync("Second Middleware out. \r\n");
            });

            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Third Middleware in. \r\n");
                await next.Invoke();
                await context.Response.WriteAsync("Third Middleware out. \r\n");
            });

 

输出结果:

First Middleware in. 
Second Middleware in. 
Second Middleware out. 
First Middleware out. 

 

 

3.中间件使用

3.1 Run (终端中间件)

Run方法运行一个委托,在委托终止了管道的运行,输出结果"终端中间件",这种中间件称为终端中间件。在Startup.cs中有如下代码:

app.Run(async (context) =>
{
    await context.Response.WriteAsync("终端中间件");
});

//其他中间件
......

 

3.2 Map (约束终端中间件)

Map匹配短路管道,匹配HttpContext.Request.Path的预设值。

            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("First Middleware in. \r\n");
                await next.Invoke();
                await context.Response.WriteAsync("First Middleware out. \r\n");
            });


            app.Map("/second", mapApp =>
            {
                mapApp.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("Second Middleware in. \r\n");
                    await next.Invoke();
                    await context.Response.WriteAsync("Second Middleware out. \r\n");
                });                
            });

            app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Third Middleware in. \r\n");
                await next.Invoke();
                await context.Response.WriteAsync("Third Middleware out. \r\n");
            });

输出结果:

First Middleware in. 
Third Middleware in. 
Third Middleware out. 
First Middleware out. 

如果使用是:http://localhost:端口号/second访问,输出结果:

First Middleware in. 
Second Middleware in. 
Second Middleware out. 
First Middleware out. 

 

3.3 自定义中间件

自定义一个中间件类

    public class RequestMiddleware
    {
        private readonly RequestDelegate _next;
        public RequestMiddleware(RequestDelegate next
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            //逻辑
            ......
            
            return _next(httpContext);
        }
    }

添加扩展方法(使用静态方法包装)

 

    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseRequestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestMiddleware>();
        }
    }

 

 

 

4.注册中间件

4.1 全局注册

public void Configure(IApplicationBuilder app)
{
  //....

  app.UseMiddleware<RequestMiddleware>(); 
    
    //如果添加扩展方法,可以这样写
    //app.UseRequestMiddleware();
    
}

4.2 局部注册

[MiddlewareFilter(typeof(RequestMiddleware))]
public class MyController : Controller
{

    [MiddlewareFilter(typeof(RequestMiddleware))]
    public IActionResult Index()
    {
        // ...
    }
}

 

posted @ 2020-07-13 17:07  落叶窥秋  阅读(224)  评论(0编辑  收藏  举报