当KestrelServer启动时,会绑定相应的IP地址,同时在绑定时将加入HttpConnectionMiddleware作为终端连接的中间件。

 public async Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken)
{
try
{
... async Task OnBind(ListenOptions endpoint)
{
// Add the HTTP middleware as the terminal connection middleware
endpoint.UseHttpServer(endpoint.ConnectionAdapters, ServiceContext, application, endpoint.Protocols); var connectionDelegate = endpoint.Build(); // Add the connection limit middleware
if (Options.Limits.MaxConcurrentConnections.HasValue)
{
connectionDelegate = new ConnectionLimitMiddleware(connectionDelegate, Options.Limits.MaxConcurrentConnections.Value, Trace).OnConnectionAsync;
} var connectionDispatcher = new ConnectionDispatcher(ServiceContext, connectionDelegate);
var transport = _transportFactory.Create(endpoint, connectionDispatcher);
_transports.Add(transport); await transport.BindAsync().ConfigureAwait(false);
} await AddressBinder.BindAsync(_serverAddresses, Options, Trace, OnBind).ConfigureAwait(false);
} ...
}
 public static IConnectionBuilder UseHttpServer<TContext>(this IConnectionBuilder builder, IList<IConnectionAdapter> adapters, ServiceContext serviceContext, IHttpApplication<TContext> application, HttpProtocols protocols)
{
var middleware = new HttpConnectionMiddleware<TContext>(adapters, serviceContext, application, protocols);
return builder.Use(next =>
{
return middleware.OnConnectionAsync;
});
}

当请求抵达此中间件时,在其OnConnectionAsync方法里会创建HttpConnection对象,并通过该对象处理请求

 public async Task OnConnectionAsync(ConnectionContext connectionContext)
{
... var connection = new HttpConnection(httpConnectionContext);
_serviceContext.ConnectionManager.AddConnection(httpConnectionId, connection); try
{
var processingTask = connection.ProcessRequestsAsync(_application); ...
}
...
}

ProcessRequestsAsync方法内部会根据HTTP协议的不同创建Http1Connection或者Http2Connection对象,一般为Http1Connection。

 public async Task ProcessRequestsAsync<TContext>(IHttpApplication<TContext> httpApplication)
{
try
{
... lock (_protocolSelectionLock)
{
// Ensure that the connection hasn't already been stopped.
if (_protocolSelectionState == ProtocolSelectionState.Initializing)
{
switch (SelectProtocol())
{
case HttpProtocols.Http1:
// _http1Connection must be initialized before adding the connection to the connection manager
requestProcessor = _http1Connection = CreateHttp1Connection(_adaptedTransport, application);
_protocolSelectionState = ProtocolSelectionState.Selected;
break;
case HttpProtocols.Http2:
// _http2Connection must be initialized before yielding control to the transport thread,
// to prevent a race condition where _http2Connection.Abort() is called just as
// _http2Connection is about to be initialized.
requestProcessor = CreateHttp2Connection(_adaptedTransport, application);
_protocolSelectionState = ProtocolSelectionState.Selected;
break;
case HttpProtocols.None:
// An error was already logged in SelectProtocol(), but we should close the connection.
Abort(ex: null);
break;
default:
// SelectProtocol() only returns Http1, Http2 or None.
throw new NotSupportedException($"{nameof(SelectProtocol)} returned something other than Http1, Http2 or None.");
} _requestProcessor = requestProcessor;
}
} if (requestProcessor != null)
{
await requestProcessor.ProcessRequestsAsync(httpApplication);
} await adaptedPipelineTask;
await _socketClosedTcs.Task;
}
...
}

Http1Connection父类HttpProtocol里的ProcessRequests方法会创建一个Context对象,但这还不是最终要找到的HttpContext。

 private async Task ProcessRequests<TContext>(IHttpApplication<TContext> application)
{
// Keep-alive is default for HTTP/1.1 and HTTP/2; parsing and errors will change its value
_keepAlive = true; while (_keepAlive)
{
... var httpContext = application.CreateContext(this); try
{
KestrelEventSource.Log.RequestStart(this); // Run the application code for this request
await application.ProcessRequestAsync(httpContext); if (_ioCompleted == )
{
VerifyResponseContentLength();
}
}
...
}
}

在HostingApplication类中会看到HttpContext原来是由HttpContextFactory工厂类生成的。

 public Context CreateContext(IFeatureCollection contextFeatures)
{
var context = new Context();
var httpContext = _httpContextFactory.Create(contextFeatures); _diagnostics.BeginRequest(httpContext, ref context); context.HttpContext = httpContext;
return context;
}

HttpContextFactory类才是最后的一站。

 public HttpContext Create(IFeatureCollection featureCollection)
{
if (featureCollection == null)
{
throw new ArgumentNullException(nameof(featureCollection));
} var httpContext = new DefaultHttpContext(featureCollection);
if (_httpContextAccessor != null)
{
_httpContextAccessor.HttpContext = httpContext;
} var formFeature = new FormFeature(httpContext.Request, _formOptions);
featureCollection.Set<IFormFeature>(formFeature); return httpContext;
}

生成的HttpContext对象最终传递到IHttpApplication的ProcessRequestAsync方法。之后的事情便是WebHost与HostingApplication的工作了。

请求(Request),响应(Response),会话(Session)这些与HTTP接触时最常见到的名词,都出现在HttpContext对象中。说明在处理HTTP请求时,若是需要获取这些相关信息,完全可以通过调用其属性而得到。

通过传递一个上下文环境参数,以协助获取各环节处理过程中所需的信息,在各种框架中是十分常见的作法。ASP.NET Core里的用法并无特别的创新,但其实用性还是毋庸置疑的。如果想要构建自己的框架时,不妨多参考下ASP.NET Core里的代码,毕竟它已是一个较成熟的产品,其中有许多值得借鉴的地方。

最新文章

  1. noip2016代码
  2. 【转】Docker 常用命令
  3. Ubuntu anzhuang
  4. 小木棍 (codevs 3498)题解
  5. HTML5+CSS3+JQuery打造自定义视频播放器
  6. Git学习笔记--Git常用命令
  7. C++类的封装_工程
  8. ExecutorService invokeAll 实例(转)
  9. OBS源码解析(3)OBSApp类介绍
  10. Oracle安装11.2.0.4.180116补丁及如何检查数据库安装补丁
  11. react native中一次错误排查 Error:Error: Duplicate resources
  12. Javascript reduce方法
  13. 学习使用JUnit4进行单元测试
  14. go语言中的函数
  15. OSI与TCP/IP模型
  16. Spring学习之路-SpringBoot简单入门
  17. Monad、Actor与并发编程--基于线程与基于事件的并发编程之争
  18. C语言课程设计-保安值班系统支持任意输入保安值班时间
  19. 第三百六十九节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)用Django实现搜索功能
  20. Mysql replace into

热门文章

  1. matplotlib 中文显示问题
  2. [总结]给pcDuino v2编译Linux kernel
  3. 【翻译】Flume 1.8.0 User Guide(用户指南) Processors
  4. Codeforces 863 简要题解
  5. 去除最后一个li的样式
  6. NIOS II 之串口学习
  7. [转]数据库中间件 MyCAT源码分析——跨库两表Join
  8. JVM中的堆和栈
  9. python opencv 处理文件、摄像头、图形化界面
  10. Maven2-坐标