如果你想深刻理解ASP.NET Core请求处理管道,可以试着写一个自定义的Server

我们在上面对ASP.NET Core默认提供的具有跨平台能力的KestrelServer进行了详细介绍(《聊聊ASP.NET Core默认提供的这个跨平台的服务器——KestrelServer》),为了让读者朋友们对管道中的Server具有更加深刻的认识,接下来我们采用实例演示的形式创建一个自定义的Server。这个自定义的Server直接利用HttpListener来完成针对请求的监听、接收和响应,我们将其命名为HttpListenerServer。在正式介绍HttpListenerServer的设计和实现之前,我们先来显示一下如何将它应用到 一个具体的Web应用中。

一、HttpListenerServer的使用

我们依然采用最简单的Hello World应用来演示针对HttpListenerServer的应用,所以我们在Startup类的Configure方法中编写如下的程序直接响应一个“Hello World”字符串。

   1: public class Startup
   2: {

   3:     public void Configure(IApplicationBuilder app)

   4:     {

   5:         app.Run(context => context.Response.WriteAsync("Hello World!"));

   6:     }

   7: }

在作为程序入口的Main方法中,我们直接创建一个WebHostBuilder对象并调用扩展方法UseHttpListener完成针对自定义HttpListenerServer的注册。我们接下来调用UseStartup方法注册上面定义的这个启动类型,然后调用Build方法创建一个WebHost对象,最后调用Run方法运行这个作为宿主的WebHost。

   1: public class Program
   2: {

   3:     public static void Main()

   4:     {

   5:         new WebHostBuilder()

   6:             .UseHttpListener()

   7:             .UseStartup<Startup>()

   8:             .Build()

   9:             .Run();

  10:     }

  11: }

  12:  

  13: public static class WebHostBuilderExtensions

  14: {

  15:     public static IWebHostBuilder UseHttpListener(this IWebHostBuilder builder)

  16:     {

  17:         builder.ConfigureServices(services => services.AddSingleton<IServer, HttpListenerServer>());

  18:         return builder;

  19:     }

  20: }

我们自定义的扩展方法UseHttpListener的逻辑很简单,它只是调用WebHostBuilder的ConfigureServices方法将我们自定义的HttpListenerServer类型以单例模式注册到指定的ServiceCollection上而已。我们直接运行这个程序并利用浏览器访问默认的监听地址(http://localhost:5000),服务端响应的“Hello World”字符串会按照如下图所示的形式显示在浏览器上。

二、总体设计

接下来我们来介绍一下HttpListenerServer的大体涉及。除了HttpListenerServer这个实现了IServer的自定义Server类型之外,我们只定义了一个名为HttpListenerServerFeature的特性类型,下图所示的UML基本上体现了HttpListenerServer的总体设计。

三、HttpListenerServerFeature

如果我们利用HttpListener来监听请求,它会为接收到的每次请求创建一个属于自己的上下文,具体来说这是一个类型为HttpListenerContext对象。我们可以利用这个HttpListenerContext对象获取所有与请求相关的信息,针对请求的任何响应也都是利用它完成的。上面这个HttpListenerServerFeature实际上就是对这个作为原始上下文的HttpListenerContext对象的封装,或者说它是管道使用的DefaultHttpContext与这个原始上下文之间沟通的中介。

如下所示的代码片段展示了HttpListenerServerFeature类型的完整定义。简单起见,我们并没有实现上面提到过的所有特性接口,而只是选择性地实现了IHttpRequestFeature和IHttpResponseFeature这两个最为核心的特性接口。它的构造函数除了具有一个类型为HttpListenerContext的参数之外,还具有一个字符串的参数pathBase用来指定请求URL的基地址(对应IHttpRequestFeature的PathBase属性),我们利用它来计算请求URL的相对地址(对应IHttpRequestFeature的Path属性)。IHttpRequestFeature和IHttpResponseFeature中定义的属性都可以直接利用HttpListenerContext对应的成员来实现,这方面并没有什么特别之处。

   1: public class HttpListenerServerFeature : IHttpRequestFeature, IHttpResponseFeature
   2: {

   3:     private readonly HttpListenerContext     httpListenerContext;

   4:     private string            queryString;

   5:     private IHeaderDictionary         requestHeaders;

   6:     private IHeaderDictionary         responseHeaders;

   7:     private string            protocol;

   8:     private readonly string       pathBase;

   9:  

  10:     public HttpListenerServerFeature(HttpListenerContext httpListenerContext, string pathBase)

  11:     {

  12:         this.httpListenerContext     = httpListenerContext;

  13:         this.pathBase         = pathBase;

  14:     }

  15:  

  16:     #region IHttpRequestFeature

  17:  

  18:     Stream IHttpRequestFeature.Body

  19:     {

  20:         get { return httpListenerContext.Request.InputStream; }

  21:         set { throw new NotImplementedException(); }

  22:     }

  23:  

  24:     IHeaderDictionary IHttpRequestFeature.Headers

  25:     {

  26:         get { return requestHeaders 

  27:          ?? (requestHeaders = GetHttpHeaders(httpListenerContext.Request.Headers)); }

  28:         set { throw new NotImplementedException(); }

  29:     }

  30:  

  31:     string IHttpRequestFeature.Method

  32:     {

  33:         get { return httpListenerContext.Request.HttpMethod; }

  34:         set { throw new NotImplementedException(); }

  35:     }

  36:  

  37:     string IHttpRequestFeature.Path

  38:     {

  39:         get { return httpListenerContext.Request.RawUrl.Substring(pathBase.Length);}

  40:         set { throw new NotImplementedException(); }

  41:     }

  42:  

  43:     string IHttpRequestFeature.PathBase

  44:     {

  45:         get { return pathBase; }

  46:         set { throw new NotImplementedException(); }

  47:     }

  48:  

  49:     string IHttpRequestFeature.Protocol

  50:     {

  51:         get{ return protocol ?? (protocol = this.GetProtocol());}

  52:         set { throw new NotImplementedException(); }

  53:     }

  54:  

  55:     string IHttpRequestFeature.QueryString

  56:     {

  57:         Get { return queryString ?? (queryString = this.ResolveQueryString());}

  58:         set { throw new NotImplementedException(); }

  59:     }

  60:  

  61:     string IHttpRequestFeature.Scheme

  62:     {

  63:         get { return httpListenerContext.Request.IsWebSocketRequest ? "https" : "http"; }

  64:         set { throw new NotImplementedException(); }

  65:     }

  66:     #endregion

  67:  

  68:     #region IHttpResponseFeature

  69:     Stream IHttpResponseFeature.Body

  70:     {

  71:         get { return httpListenerContext.Response.OutputStream; }

  72:         set { throw new NotImplementedException(); }

  73:     }

  74:  

  75:     string IHttpResponseFeature.ReasonPhrase

  76:     {

  77:         get { return httpListenerContext.Response.StatusDescription; }

  78:         set { httpListenerContext.Response.StatusDescription = value; }

  79:     }

  80:  

  81:     bool IHttpResponseFeature.HasStarted

  82:     {

  83:         get { return httpListenerContext.Response.SendChunked; }

  84:     }

  85:  

  86:     IHeaderDictionary IHttpResponseFeature.Headers

  87:     {

  88:         get { return responseHeaders 

  89:             ?? (responseHeaders = GetHttpHeaders(httpListenerContext.Response.Headers)); }

  90:         set { throw new NotImplementedException(); }

  91:     }

  92:     int IHttpResponseFeature.StatusCode

  93:     {

  94:         get { return httpListenerContext.Response.StatusCode; }

  95:         set { httpListenerContext.Response.StatusCode = value; }

  96:     }

  97:  

  98:     void IHttpResponseFeature.OnCompleted(Func<object, Task> callback, object state)

  99:     {

 100:         throw new NotImplementedException();

 101:     }

 102:  

 103:     void IHttpResponseFeature.OnStarting(Func<object, Task> callback, object state)

 104:     {

 105:         throw new NotImplementedException();

 106:     }

 107:     #endregion

 108:  

 109:     private string ResolveQueryString()

 110:     {

 111:         string queryString = "";

 112:         var collection = httpListenerContext.Request.QueryString;

 113:         for (int i = 0; i < collection.Count; i++)

 114:         {

 115:             queryString += $"{collection.GetKey(i)}={collection.Get(i)}&";

 116:         }

 117:         return queryString.TrimEnd(‘&‘);

 118:     }

 119:  

 120:     private IHeaderDictionary GetHttpHeaders(NameValueCollection headers)

 121:     {

 122:         HeaderDictionary dictionary = new HeaderDictionary();

 123:         foreach (string name in headers.Keys)

 124:         {

 125:             dictionary[name] = new StringValues(headers.GetValues(name));

 126:         }

 127:         return dictionary;

 128:     }

 129:  

 130:     private string GetProtocol()

 131:     {

 132:         HttpListenerRequest request = httpListenerContext.Request;

 133:         Version version = request.ProtocolVersion;

 134:         return string.Format("{0}/{1}.{2}", request.IsWebSocketRequest ? "HTTPS" : "HTTP", version.Major, version.Minor);

 135:     }

 136: }

四、HttpListenerServer

接下来我们来看看HttpListenerServer的定义。如下面的代码片段所示,用来监听请求的HttpListener在构造函数中被创建,与此同时,我们会创建一个用于获取监听地址的ServerAddressesFeature对象并将其添加到属于自己的特性列表中。当HttpListenerServer随着Start方法的调用而被启动后,它将这个ServerAddressesFeature对象提取出来,然后利用它得到所有的地址并添加到HttpListener的Prefixes属性表示的监听地址列表中。接下来,HttpListener的Start方法被调用,并在一个无限循环中开启请求的监听与接收。

   1: public class HttpListenerServer : IServer
   2: {

   3:     private readonly HttpListener listener;

   4:  

   5:     public IFeatureCollection Features { get; } = new FeatureCollection();

   6:     

   7:     public HttpListenerServer()

   8:     {

   9:         listener = new HttpListener();

  10:         this.Features.Set<IServerAddressesFeature>(new ServerAddressesFeature());

  11:     }

  12:  

  13:     public void Dispose()

  14:     {

  15:         listener.Stop();

  16:     }

  17:  

  18:     public void Start<TContext>(IHttpApplication<TContext> application)

  19:     {

  20:         foreach (string address in this.Features.Get<IServerAddressesFeature>().Addresses)

  21:         {

  22:             listener.Prefixes.Add(address.TrimEnd(‘/‘) + "/");

  23:         }

  24:  

  25:         listener.Start();

  26:         while (true)

  27:         {

  28:             HttpListenerContext httpListenerContext = listener.GetContext();

  29:  

  30:             string listenUrl = this.Features.Get<IServerAddressesFeature>().Addresses.First(address => httpListenerContext.Request.Url.IsBaseOf(new Uri(address)));

  31:             string pathBase = new Uri(listenUrl).LocalPath.TrimEnd(‘/‘) ;

  32:             HttpListenerServerFeature feature = new HttpListenerServerFeature(httpListenerContext, pathBase);

  33:  

  34:             FeatureCollection features = new FeatureCollection();

  35:             features.Set<IHttpRequestFeature>(feature);

  36:             features.Set<IHttpResponseFeature>(feature);

  37:             TContext context = application.CreateContext(features);

  38:  

  39:             application.ProcessRequestAsync(context).ContinueWith(task =>

  40:             {

  41:                 httpListenerContext.Response.Close();

  42:                 application.DisposeContext(context, task.Exception);

  43:             });

  44:         }

  45:     }

  46: }

HttpListener的GetContext方法以同步的方式监听请求,并利用接收到的请求创建返回的HttpListenerContext对象。我们利用它解析出当前请求的基地址,并进一步创建出描述当前原始上下文的HttpListenerServerFeature。接下来我们将这个对象分别采用特性接口IHttpRequestFeature和IHttpResponseFeature添加到创建的FeatureCollection对象中。然后我们将这个FeatureCollection作为参数调用HttpApplication的CreateContext创建出上下文对象,并将其作为参数调用HttpApplication的ProcessContext方法让注册的中间件来逐个地对请求进行处理。

时间: 2024-07-29 20:12:58

如果你想深刻理解ASP.NET Core请求处理管道,可以试着写一个自定义的Server的相关文章

ASP.NET Core 1.1 静态文件、路由、自定义中间件、身份验证简介

概述 之前写过一篇关于<ASP.NET Core 1.0 静态文件.路由.自定义中间件.身份验证简介>的文章,主要介绍了ASP.NET Core中StaticFile.Middleware.CustomizeMiddleware和Asp.NetCore Identity.但是由于所有的ASP.NET Core的版本有些老,所以,此次重写一次.使用最新的ASP.NET Core 1.1版本.对于ASP.NET Core 1.1 Preview 1会在以后的文章中介绍 目录 使用静态文件 使用路由

[ASP.NET Core 3框架揭秘] 依赖注入:一个Mini版的依赖注入框架

在前面的章节中,我们从纯理论的角度对依赖注入进行了深入论述,我们接下来会对.NET Core依赖注入框架进行单独介绍.为了让读者朋友能够更好地理解.NET Core依赖注入框架的设计与实现,我们按照类似的原理创建了一个简易版本的依赖注入框架,也就是我们在前面多次提及的Cat. 源代码下载 普通服务的注册与消费泛型服务的注册与消费多服务实例的提供服务实例的生命周期 一.编程体验 虽然我们对这个名为Cat的依赖注入框架进行了最大限度的简化,但是与.NET Core框架内部使用的真实依赖注入框架相比,

ASP.NET MVC请求处理管道生命周期的19个关键环节(7-12)

转自http://www.cnblogs.com/darrenji/p/3795676.html 在上一篇"ASP.NET MVC请求处理管道生命周期的19个关键环节(1-6) ",体验了1-6关键环节,本篇继续. ⑦根据IsapiWorkerRequest对象,HttpRuntime创建HttpContext对象 ⑧HttpApplicationFactory创建新的或者从HttpApplication池获取现有的.可用的HttpApplication对象 HttpApplicati

ASP.NET MVC请求处理管道生命周期的19个关键环节(13-19)

转自:http://www.cnblogs.com/darrenji/p/3795690.html 在上一篇"ASP.NET MVC请求处理管道生命周期的19个关键环节(7-12) ",体验了7-12关键环节,本篇继续. ⒀当请求到达UrlRoutingModule的时候,UrlRoutingModule取出请求中的Controller.Action等RouteData信息,与路由表中的所有规则进行匹配,若匹配,把请求交给IRouteHandler,即MVCRouteHandler M

ASP.NET MVC请求处理管道生命周期的19个关键环节(1-6)

ASP.NET和ASP.NET MVC的HttpApplication请求处理管道有共同的部分和不同之处,本系列将体验ASP.NET MVC请求处理管道生命周期的19个关键环节. ①以IIS6.0为例,首先由w3wp.exe维护着一个工作进程 ②如果是第一次加载,由Aspnet_isapi.dll加载.NET运行时 ③一个工作进程里有一个应用程序池,其中可以承载多个应用程序域AppDomain ④HTTP.SYS接收请求,通过应用程序域工厂AppDomainFactory创建应用程序域AppDo

全面理解 ASP.NET Core 依赖注入

DI在.NET Core里面被提到了一个非常重要的位置, 这篇文章主要再给大家普及一下关于依赖注入的概念,身边有工作六七年的同事还个东西搞不清楚.另外再介绍一下.NET  Core的DI实现以及对实例生命周期的管理(这个是经常面试会问到的问题).最后再给大家简单介绍一下在控制台以及Mvc下如何使用DI,以及如何把默认的Service Container 替换成Autofac. 我录了一些关于ASP.NET Core的入门视频:有兴趣的同学可以去看看.  http://www.cnblogs.co

ASP.NET Core HTTP 管道中的那些事儿

IApplicationBuilder IApplicationBuilder 是应用大家最熟悉它的地方应该就是位于 Startup.cs 文件中的 Configure 方法了吧 public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory){     app.UseDeveloperExceptionPage();     app.UseStaticFiles();     app.UseMvc(); }

ASP.NET Core真实管道详解[1]

ASP.NET Core管道虽然在结构组成上显得非常简单,但是在具体实现上却涉及到太多的对象,所以我们在 <ASP.NET Core管道深度剖析[共4篇]> 中围绕着一个经过极度简化的模拟管道讲述了真实管道构建的方式以及处理HTTP请求的流程.在这个系列 中,我们会还原构建模拟管道时刻意舍弃和改写的部分,想读者朋友们呈现一个真是的HTTP请求处理管道. ASP.NET Core 的请求处理管道由一个Server和一组有序排列的中间件构成,前者仅仅完成基本的请求监听.接收和响应的工作,请求接收之

ASP.NET Core真实管道详解[1]:中间件是个什么东西?

ASP.NET Core管道虽然在结构组成上显得非常简单,但是在具体实现上却涉及到太多的对象,所以我们在 <ASP.NET Core管道深度剖析[共4篇]> 中围绕着一个经过极度简化的模拟管道讲述了真实管道构建的方式以及处理HTTP请求的流程.在这个系列 中,我们会还原构建模拟管道时刻意舍弃和改写的部分,想读者朋友们呈现一个真是的HTTP请求处理管道. ASP.NET Core 的请求处理管道由一个Server和一组有序排列的中间件构成,前者仅仅完成基本的请求监听.接收和响应的工作,请求接收之