zoukankan      html  css  js  c++  java
  • Asp.Net Core学习笔记5——中间件

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

    1.中间件

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

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

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

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

    输出结果:

    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. 
    ");
                    await next.Invoke();
                    await context.Response.WriteAsync("First Middleware out. 
    ");
                });
    
    
                app.Map("/second", mapApp =>
                {
                    mapApp.Use(async (context, next) =>
                    {
                        await context.Response.WriteAsync("Second Middleware in. 
    ");
                        await next.Invoke();
                        await context.Response.WriteAsync("Second Middleware out. 
    ");
                    });                
                });
    
                app.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("Third Middleware in. 
    ");
                    await next.Invoke();
                    await context.Response.WriteAsync("Third Middleware out. 
    ");
                });

    输出结果:

    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()
        {
            // ...
        }
    }
  • 相关阅读:
    [Qt] 文本文件读写, 摘自官方文档
    [Windows] Socket Server Failed to bind, error 10048
    lodctr /R 失败的情况
    ModuleNotFoundError: No module named 'sklearn.cross_validation'
    [Qt] 通过socket将另一个程序的某个窗口调到最前端
    SortedDictionary<TKey, TValue> 类 表示根据键进行排序的键/值对的集合。
    finally不管有没有错都会运行 finally 块用于清除 try 块中分配的任何资源,以及运行任何即使在发生异常时也必须执行的代码
    HttpWebRequest使用证书请求
    string StartsWith 方法 Https
    设置https验证方式
  • 原文地址:https://www.cnblogs.com/nmmking/p/13293491.html
Copyright © 2011-2022 走看看