AspNetCore 请求处理管道--WebHost

AspNetCore 请求处理流程

ASP.NET Core 请求处理管道

思维导图

其他

  1. 中间件

    • 中间件规范

      • 应该定义成实例类,不能定义成静态类。
      • 具有一个有效的公共构造函数。这个构造函数的第一个参数类型必须为RequestDelegate,代表对请求的后续操作(可以视为下一个注册的中间件),至于后续参数的个数和类型则不作要求。后续参数可以被依赖注入
      • 针对请求的处理定义在一个名为Invoke的公共实例方法,其返回类型为Task。该方法的第一个参数类型为HttpContext,代表当前HTTP上下文。我们可以为这个方法定义任意数量和类型的后续参数,当这个方法被执行的时候,系统将会采用依赖注入的方式提供响应的服务来为这个参数赋值。
      • 示例:
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        public class ContentMiddleare
        {
        public RequestDelegate _next;
        public byte[] _content;
        public string _contentType;

        public ContentMiddleare(RequestDelegate next, byte[] content, string contentType)
        {
        _next = next;
        _content = content;
        _contentType = contentType;
        }

        public async Task Invoke(HttpContext context, ILoggerFactory loggerFactory)
        {
        loggerFactory.CreateLogger<ContentMiddleare>().LogInformation($"Write content ({_contentType})");
        context.Response.ContentType = _contentType;
        await context.Response.Body.WriteAsync(_content,0, _content.Length);
        }
        }
    • IMiddlewareIMiddlewareFactory

  2. 第三方 DI框架 整合

    • 规范
      1. 标配:Startup 中带返回值 IServiceProviderConfigureServices
        1
        2
        3
        4
        public IServiceProvider ConfigureServices(IServiceCollection svcs)
        {
        return Cat.Instance.Register(svcs.AddSingleton<IBaz, Baz>());
        }