转载

如果你想深刻理解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”字符串。

 public class Startup  {      public void Configure(IApplicationBuilder app)      {          app.Run(context => context.Response.WriteAsync("Hello World!"));      }  } 

在作为程序入口的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: }
  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”字符串会按照如下图所示的形式显示在浏览器上。

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

二、总体设计

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

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

三、HttpListenerServerFeature

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

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

 public class HttpListenerServerFeature : IHttpRequestFeature, IHttpResponseFeature  {      private readonly HttpListenerContext     httpListenerContext;      private string            queryString;      private IHeaderDictionary         requestHeaders;      private IHeaderDictionary         responseHeaders;      private string            protocol;      private readonly string       pathBase;         public HttpListenerServerFeature(HttpListenerContext httpListenerContext, string pathBase)      {          this.httpListenerContext     = httpListenerContext;          this.pathBase         = pathBase;      }         #region IHttpRequestFeature         Stream IHttpRequestFeature.Body      {          get { return httpListenerContext.Request.InputStream; }          set { throw new NotImplementedException(); }      }         IHeaderDictionary IHttpRequestFeature.Headers      {          get { return requestHeaders            ?? (requestHeaders = GetHttpHeaders(httpListenerContext.Request.Headers)); }          set { throw new NotImplementedException(); }      }         string IHttpRequestFeature.Method      {          get { return httpListenerContext.Request.HttpMethod; }          set { throw new NotImplementedException(); }      }         string IHttpRequestFeature.Path      {          get { return httpListenerContext.Request.RawUrl.Substring(pathBase.Length);}          set { throw new NotImplementedException(); }      }         string IHttpRequestFeature.PathBase      {          get { return pathBase; }          set { throw new NotImplementedException(); }      }         string IHttpRequestFeature.Protocol      {          get{ return protocol ?? (protocol = this.GetProtocol());}          set { throw new NotImplementedException(); }      }         string IHttpRequestFeature.QueryString      {          Get { return queryString ?? (queryString = this.ResolveQueryString());}          set { throw new NotImplementedException(); }      }         string IHttpRequestFeature.Scheme      {          get { return httpListenerContext.Request.IsWebSocketRequest ? "https" : "http"; }          set { throw new NotImplementedException(); }      }      #endregion         #region IHttpResponseFeature      Stream IHttpResponseFeature.Body      {          get { return httpListenerContext.Response.OutputStream; }          set { throw new NotImplementedException(); }      }         string IHttpResponseFeature.ReasonPhrase      {          get { return httpListenerContext.Response.StatusDescription; }          set { httpListenerContext.Response.StatusDescription = value; }      }         bool IHttpResponseFeature.HasStarted      {          get { return httpListenerContext.Response.SendChunked; }      }         IHeaderDictionary IHttpResponseFeature.Headers      {          get { return responseHeaders               ?? (responseHeaders = GetHttpHeaders(httpListenerContext.Response.Headers)); }          set { throw new NotImplementedException(); }      }      int IHttpResponseFeature.StatusCode      {          get { return httpListenerContext.Response.StatusCode; }          set { httpListenerContext.Response.StatusCode = value; }      }         void IHttpResponseFeature.OnCompleted(Func<object, Task> callback, object state)      {          throw new NotImplementedException();      }         void IHttpResponseFeature.OnStarting(Func<object, Task> callback, object state)      {          throw new NotImplementedException();      }      #endregion         private string ResolveQueryString()      {          string queryString = "";          var collection = httpListenerContext.Request.QueryString;          for (int i = 0; i < collection.Count; i++)          {              queryString += $"{collection.GetKey(i)}={collection.Get(i)}&";          }          return queryString.TrimEnd('&');      }         private IHeaderDictionary GetHttpHeaders(NameValueCollection headers)      {          HeaderDictionary dictionary = new HeaderDictionary();          foreach (string name in headers.Keys)          {              dictionary[name] = new StringValues(headers.GetValues(name));          }          return dictionary;      }         private string GetProtocol()      {          HttpListenerRequest request = httpListenerContext.Request;          Version version = request.ProtocolVersion;          return string.Format("{0}/{1}.{2}", request.IsWebSocketRequest ? "HTTPS" : "HTTP", version.Major, version.Minor);      }  } 


四、HttpListenerServer

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

 public class HttpListenerServer : IServer  {      private readonly HttpListener listener;         public IFeatureCollection Features { get; } = new FeatureCollection();            public HttpListenerServer()      {          listener = new HttpListener();          this.Features.Set<IServerAddressesFeature>(new ServerAddressesFeature());      }         public void Dispose()      {          listener.Stop();      }         public void Start<TContext>(IHttpApplication<TContext> application)      {          foreach (string address in this.Features.Get<IServerAddressesFeature>().Addresses)          {              listener.Prefixes.Add(address.TrimEnd('/') + "/");          }             listener.Start();          while (true)          {              HttpListenerContext httpListenerContext = listener.GetContext();                 string listenUrl = this.Features.Get<IServerAddressesFeature>().Addresses.First(address => httpListenerContext.Request.Url.IsBaseOf(new Uri(address)));              string pathBase = new Uri(listenUrl).LocalPath.TrimEnd('/') ;              HttpListenerServerFeature feature = new HttpListenerServerFeature(httpListenerContext, pathBase);                 FeatureCollection features = new FeatureCollection();              features.Set<IHttpRequestFeature>(feature);              features.Set<IHttpResponseFeature>(feature);              TContext context = application.CreateContext(features);                 application.ProcessRequestAsync(context).ContinueWith(task =>              {                  httpListenerContext.Response.Close();                  application.DisposeContext(context, task.Exception);              });          }      }  } 

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

原文  http://www.cnblogs.com/artech/p/stomized-server.html
正文到此结束
Loading...