欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET Core启动流程

程序员文章站 2022-03-07 21:45:49
ASP.NET Core启动流程new WebHostBuilder()初始化类型WebHostBuilder的属性IServer _serverList _configuresUseHttpListener()这是IWebHostBuilder下面的一个扩展方法UseServer(new HttpListenerServer(urls))new HttpListenerServer(urls)HttpListener _httpListener....

ASP.NET Core启动流程

ASP.NET Core启动流程

new WebHostBuilder()

初始化类型WebHostBuilder的属性

IServer _server

List<Action> _configures

UseHttpListener()

这是IWebHostBuilder下面的一个扩展方法

UseServer(new HttpListenerServer(urls))

  • new HttpListenerServer(urls)

    • HttpListener _httpListener

    • string[] _urls

      httpServer要监听的请求地址

  • UseServer(new HttpListenerServer(urls))

    • 给IServer _server赋值,值为HttpListenerServer实例
  • return IWebHostBuilder

Configure(app => app.Use())

配置应用程序,中间件

给List<Action> _configures赋值,值为Action

return IWebHostBuilder

Build()

new ApplicationBuilder()

  • 初始化List<Func<RequestDelegate, RequestDelegate>> _middlewares

遍历List<Action> _configures

  • 赋值为空的ApplicationBuilder()

return new WebHost(_server, builder.Build())

参数分别为HTTPServer,(new ApplicationBuilder()).Build()

  • builder.Build()

    • _middlewares.Reverse()

      反转所有的中间件

    • return httpContext =>{… };

      构建中间件

      • RequestDelegate next = _ => { _.Response.StatusCode = 404; return Task.CompletedTask; };

        定义请求处理失败的中间件(委托)

      • foreach (var middleware in _middlewares)
        {
        next = middleware(next);
        }

        将所有的中间件处理成委托链表

      • return next(httpContext);

        返回请求的处理委托链表

StartAsync()

_server.StartAsync(_handler)

  • Array.ForEach(_urls, url => _httpListener.Prefixes.Add(url));

    将需要监听的http地址赋值给HTTPServer

  • _httpListener.Start();

    启动HTTPServer

  • while (true){…}

    监听HTTP请求

    • var listenerContext = await _httpListener.GetContextAsync();

      服务器生成HTTP请求原始上下文,包括原始request和response

    • var feature = new HttpListenerFeature(listenerContext);

      根据原始上下文生成HttpServerFeature,包括IHttpRequestFeature, IHttpResponseFeature

    • var features = new FeatureCollection()
      .Set(feature)
      .Set(feature);

      生成(初始化)FeatureCollection(值为k-v形式)
      分别设置key为IHttpRequestFeature,IHttpResponseFeature,value都是feature

    • var httpContext = new HttpContext(features);

      生成(初始化)ASP.NET Core的http请求上下文,包括HttpRequest,HttpResponse

    • await handler(httpContext);

      请求处理

    • listenerContext.Response.Close();

      发送响应到客户端,请求结束

本文地址:https://blog.csdn.net/SXML123456/article/details/107550439