在学习ASP.NET Core源码过程中,偶然看见蒋金楠老师的ASP.NET Core框架揭秘,不到200行代码实现了ASP.NET Core Mini框架,针对框架本质进行了讲解,受益匪浅,本文结合ASP.NET Core Mini框架讲述ASP.NET Core核心。

微软官网关于ASP.NET Core的概念“ASP.NET Core是一个开源和跨平台的框架,用于构建基于Web的现代互联网连接应用程序,例如Web应用程序,IoT应用程序和移动后端。 ASP.NET Core应用程序可以在.NET Core或完整的.NET Framework上运行。 它的架构旨在为部署到云或在本地运行的应用程序提供优化的开发框架。 它由模块化组件组成,开销最小,因此您可以在构建解决方案时保持灵活性。 您可以在Windows,Mac和Linux上跨平台开发和运行ASP.NET核心应用程序”。可以从定义上看出ASP.NET Core框架具有跨平台、部署灵活、模块化等特点。

ASP.NET Core Mini

 

ASP.NET Core Mini是200行代码实现的迷你版ASP.NET Core框架,有三大特点“简单”,“真实模拟”,“可执行”来让我们更加容易理解ASP.NET Core。

 

asp.net项目结构 asp.net core架构_asp.net项目结构

 

代码结构:

 

asp.net项目结构 asp.net core架构_App_02

下图是项目运行页面输出的结果:

asp.net项目结构 asp.net core架构_System_03

本文从以下五个角度讲述:

  • Program: 项目入口
  • Middleware:中间件
  • HttpContext:Http相关
  • WebHost:WebHost
  • Server:Server相关

 Program

 

1 using System.Threading.Tasks;
 2 using App.Server;
 3 using App.WebHost;
 4 
 5 namespace App
 6 {
 7     public static class Program
 8     {
 9         public static async Task Main(string[] args)
10         {
11             await CreateWebHostBuilder()
12                 .Build()
13                 .Run();
14         }
15 
16         private static IWebHostBuilder CreateWebHostBuilder()
17         {
18             return new WebHostBuilder()
19                 .UseHttpListener()
20                 .Configure(app => app
21                     .Use(Middleware.Middleware.FooMiddleware)
22                     .Use(Middleware.Middleware.BarMiddleware)
23                     .Use(Middleware.Middleware.BazMiddleware));
24         }
25     }
26 }

可以看到项目的入口是Main方法,它只做了三件事,构造WebHostBuilder,然后Build方法构造WebHost,最后Run方法启动WebHost。我们可以简单的理解WebHostBuilder作用就是为了构造WebHost,他是WebHost的构造器,而WebHost是我们Web应用的宿主。

再看CreateWebHostBuilder的方法具体干了什么。首先创建了WebHostBuilder,然后UseHttpListener配置Server(比如ASP.NET Core中的Kestrel或IIS等等),一般包括地址和端口等,最后注册一系列的中间件。

从Program可以看出整个App运行起来的流程,如下图所示:

 

asp.net项目结构 asp.net core架构_asp.net项目结构_04

 

Middleware

 

asp.net项目结构 asp.net core架构_ASP.NET Core_05

 

在看HttpContext之前,我们先来看ASP.NET Core 的Http处理管道是什么样子,上图是官方给出的管道处理图,当我们的服务器接收到一个Http请求,管道进行处理,处理后再进行返回,可以看到,我们的Http请求经过多层中间件处理最后返回。

1 using System.Threading.Tasks;
2 
3 namespace App.Middleware
4 {
5     public delegate Task RequestDelegate(HttpContext.HttpContext context);
6 }

首先来看RequestDelegate.cs,定义了一个参数类型是HttpContext,返回结果是Task的委托。

为什么会定义这个委托,可以想到一个Http请求会经过多层中间件处理,那么多层中间件处理可以想像成一个HttpHandler,他的参数就是HttpContext,返回结果是Task的委托。

asp.net项目结构 asp.net core架构_App_06

1 using App.HttpContext;
 2 
 3 namespace App.Middleware
 4 {
 5     public static class Middleware
 6     {
 7         public static RequestDelegate FooMiddleware(RequestDelegate next)
 8             => async context =>
 9             {
10                 await context.Response.WriteAsync("Foo=>");
11                 await next(context);
12             };
13 
14         public static RequestDelegate BarMiddleware(RequestDelegate next)
15             => async context =>
16             {
17                 await context.Response.WriteAsync("Bar=>");
18                 await next(context);
19             };
20 
21         public static RequestDelegate BazMiddleware(RequestDelegate next)
22             => context => context.Response.WriteAsync("Baz");
23     }
24 }

Middleware中定义了三个简单的中间件,可以看到,中间件其实就是委托,将HttpContext一层一层进行处理。

Http请求进入管道,第一个中间件处理完,把自身作为结果传输到下一个中间件进行处理,那么参数是RequestDelegate,返回值是RequestDelegate的委托就是中间件,所以中间件其实就是Func<RequestDelegate,RequestDelegate>,简单来说,中间件就是RequestDelegate的加工工厂。

asp.net项目结构 asp.net core架构_System_07

HttpContext

 

从Middleware了解到,HttpContext是RequestDelegate的参数,是每一个Middleware处理数据的来源。

我们可以这么理解,HttpContext就是我们整个Http请求中的共享资源,所以的中间件共享它,而每个中间件就是对它进行加工处理。

1 using System;
 2 using System.Collections.Specialized;
 3 using System.IO;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace App.HttpContext
 8 {
 9     public class HttpContext
10     {
11         public HttpRequest Request { get; }
12         public HttpResponse Response { get; }
13 
14         public HttpContext(IFeatureCollection features)
15         {
16             Request = new HttpRequest(features);
17             Response = new HttpResponse(features);
18         }
19     }
20 
21     public class HttpRequest
22     {
23         private readonly IHttpRequestFeature _feature;
24         
25         public Uri Url => _feature.Url;
26         
27         public NameValueCollection Headers => _feature.Headers;
28         
29         public Stream Body => _feature.Body;
30         
31         public HttpRequest(IFeatureCollection features) => _feature = features.Get<IHttpRequestFeature>();
32     }
33 
34     public class HttpResponse
35     {
36         private readonly IHttpResponseFeature _feature;
37         public HttpResponse(IFeatureCollection features) => _feature = features.Get<IHttpResponseFeature>();
38         
39         public NameValueCollection Headers => _feature.Headers;
40         public Stream Body => _feature.Body;
41 
42         public int StatusCode
43         {
44             get => _feature.StatusCode;
45             set => _feature.StatusCode = value;
46         }
47     }
48 
49     public static partial class Extensions
50     {
51         public static Task WriteAsync(this HttpResponse response, string contents)
52         {
53             var buffer = Encoding.UTF8.GetBytes(contents);
54             return response.Body.WriteAsync(buffer, 0, buffer.Length);
55         }
56     }
57 }

代码结构可以看出request和reponse构成httpcontext,也反映出httpcontext的职责:Http请求的上下文。

asp.net项目结构 asp.net core架构_ASP.NET Core_08

但是,不同的Server和单一的HttpContext之间需要如何适配呢?因为我们可以注册多样的Server,可以是IIS也可以是Kestrel还可以是这里的HttpListenerServer。

所以我们需要定义统一的request和response接口,来适配不同的Server。如下图的IHttpRequestFeature和IHttpResponseFeature。

1 using System;
 2 using System.Collections.Specialized;
 3 using System.IO;
 4 
 5 namespace App.HttpContext
 6 {
 7     public interface IHttpRequestFeature
 8     {
 9         Uri Url { get; }
10         
11         NameValueCollection Headers { get; }
12         
13         Stream Body { get; }
14     }
15 
16     public interface IHttpResponseFeature
17     {
18         int StatusCode { get; set; }
19         
20         NameValueCollection Headers { get; }
21         
22         Stream Body { get; }
23     }
24 }

在HttpListenerFeature.cs中实现request和response的接口,实现了适配不同的server。

1 using System;
 2 using System.Collections.Specialized;
 3 using System.IO;
 4 using System.Net;
 5 
 6 namespace App.HttpContext
 7 {
 8     public class HttpListenerFeature : IHttpRequestFeature, IHttpResponseFeature
 9     {
10         private readonly HttpListenerContext _context;
11 
12         public HttpListenerFeature(HttpListenerContext context) => _context = context;
13 
14         Uri IHttpRequestFeature.Url => _context.Request.Url;
15 
16         NameValueCollection IHttpRequestFeature.Headers => _context.Request.Headers;
17 
18         NameValueCollection IHttpResponseFeature.Headers => _context.Response.Headers;
19 
20         Stream IHttpRequestFeature.Body => _context.Request.InputStream;
21 
22         Stream IHttpResponseFeature.Body => _context.Response.OutputStream;
23 
24         int IHttpResponseFeature.StatusCode
25         {
26             get => _context.Response.StatusCode;
27             set => _context.Response.StatusCode = value;
28         }
29     }
30 }

至于FeatureCollection.cs,它的作用就是将从httpListenerContext中获取的Http信息存储在FeatureCollection的Dictionary里,更加方便的对HttpRequestFeature和HttpResponseFeature进行操作。

扩展方法Get和Set的作用是方便操作FeatureCollection。

1 using System;
 2 using System.Collections.Generic;
 3 
 4 namespace App.HttpContext
 5 {
 6     public interface IFeatureCollection : IDictionary<Type, object>
 7     {
 8     }
 9 
10     public class FeatureCollection : Dictionary<Type, object>, IFeatureCollection
11     {
12     }
13 
14     public static partial class Extensions
15     {
16         public static T Get<T>(this IFeatureCollection features) =>
17             features.TryGetValue(typeof(T), out var value) ? (T) value : default(T);
18 
19         public static IFeatureCollection Set<T>(this IFeatureCollection features, T feature)
20         {
21             features[typeof(T)] = feature;
22             return features;
23         }
24     }
25 }

WebHost

 

1 using System;
 2 using System.Collections.Generic;
 3 using App.Server;
 4 
 5 namespace App.WebHost
 6 {
 7     public interface IWebHostBuilder
 8     {
 9         IWebHostBuilder UseServer(IServer server);
10         
11         IWebHostBuilder Configure(Action<IApplicationBuilder> configure);
12         
13         IWebHost Build();
14     }
15 
16     public class WebHostBuilder : IWebHostBuilder
17     {
18         private IServer _server;
19         private readonly List<Action<IApplicationBuilder>> _configures = new List<Action<IApplicationBuilder>>();
20 
21         public IWebHostBuilder Configure(Action<IApplicationBuilder> configure)
22         {
23             _configures.Add(configure);
24             return this;
25         }
26 
27         public IWebHostBuilder UseServer(IServer server)
28         {
29             _server = server;
30             return this;
31         }
32 
33         public IWebHost Build()
34         {
35             var builder = new ApplicationBuilder();
36             foreach (var configure in _configures)
37             {
38                 configure(builder);
39             }
40 
41             return new WebHost(_server, builder.Build());
42         }
43     }
44 }

WebHost是我们App的宿主,通过WebHostBuild构造,代码里定义了三个方法,

  • UseServer: 配置server
  • Configure: 注册中间件
  • Build: 构造WebHost
1 using System;
 2 using System.Collections.Generic;
 3 using System.Threading.Tasks;
 4 using App.Middleware;
 5 
 6 namespace App.WebHost
 7 {
 8     public interface IApplicationBuilder
 9     {
10         IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
11 
12         RequestDelegate Build();
13     }
14 
15     public class ApplicationBuilder : IApplicationBuilder
16     {
17         private readonly List<Func<RequestDelegate, RequestDelegate>> _middlewares =
18             new List<Func<RequestDelegate, RequestDelegate>>();
19 
20         public RequestDelegate Build()
21         {
22             _middlewares.Reverse();
23             return httpContext =>
24             {
25                 RequestDelegate next = _ =>
26                 {
27                     _.Response.StatusCode = 404;
28                     return Task.CompletedTask;
29                 };
30 
31                 foreach (var middleware in _middlewares)
32                 {
33                     next = middleware(next);
34                 }
35 
36                 return next(httpContext);
37             };
38         }
39 
40         public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
41         {
42             _middlewares.Add(middleware);
43             return this;
44         }
45     }
46 }

ApplicationBuilder做了什么,Use方法我们把自定义的中间件放进集合里,而build方法就是构建webhost。首先把中间键集合顺序倒置,然后构造一个StatusCode为404的中间件,其次遍历中间件集合,最后返回构造好的管道。

如果中间件集合为空,我们返回Http 404错误。

至于为什么要Reverse(),是因为我们注册中间件的顺序与我们需要执行的顺序相反。

1 using System.Threading.Tasks;
 2 using App.Middleware;
 3 using App.Server;
 4 
 5 namespace App.WebHost
 6 {
 7     public interface IWebHost
 8     {
 9         Task Run();
10     }
11 
12     public class WebHost : IWebHost
13     {
14         private readonly IServer _server;
15         private readonly RequestDelegate _handler;
16 
17         public WebHost(IServer server, RequestDelegate handler)
18         {
19             _server = server;
20             _handler = handler;
21         }
22 
23         public Task Run() => _server.RunAsync(_handler);
24     }
25 }

WebHost只做了一件事,将我们构造的中间件管道处理器在指定Server运行起来。

Server


我们自定义一个服务器,IServer定义统一接口,HttpListenerServer实现我们自定义的Server

1 using System;
 2 using System.Linq;
 3 using System.Net;
 4 using System.Threading.Tasks;
 5 using App.HttpContext;
 6 using App.Middleware;
 7 using App.WebHost;
 8 
 9 namespace App.Server
10 {
11     public class HttpListenerServer : IServer
12     {
13         private readonly HttpListener _httpListener;
14         private readonly string[] _urls;
15 
16         public HttpListenerServer(params string[] urls)
17         {
18             _httpListener = new HttpListener();
19             _urls = urls.Any() ? urls : new[] {"http://localhost:5000/"};
20         }
21 
22         public async Task RunAsync(RequestDelegate handler)
23         {
24             Array.ForEach(_urls, url => _httpListener.Prefixes.Add(url));
25             
26             if (!_httpListener.IsListening)
27             {
28                 _httpListener.Start();
29             }
30 
31             Console.WriteLine("Server started and is listening on: {0}", string.Join(';', _urls));
32 
33             while (true)
34             {
35                 var listenerContext = await _httpListener.GetContextAsync();
36                 var feature = new HttpListenerFeature(listenerContext);
37                 var features = new FeatureCollection()
38                     .Set<IHttpRequestFeature>(feature)
39                     .Set<IHttpResponseFeature>(feature);
40                 var httpContext = new HttpContext.HttpContext(features);
41                 
42                 await handler(httpContext);
43                 
44                 listenerContext.Response.Close();
45             }
46         }
47     }
48 
49     public static class Extensions
50     {
51         public static IWebHostBuilder UseHttpListener(this IWebHostBuilder builder, params string[] urls)
52             => builder.UseServer(new HttpListenerServer(urls));
53     }
54 }

使用UseHttpListener扩展方法,指定监听地址,默认为“http://localhost:5000/”。

RunAsync方法是我们WebHost的Run方法,循环中通过调用其GetContextAsync方法实现了针对请求的监听和接收。


小结

 

看完这篇文章应该对ASP.NET Core有一定对理解,核心就是中间件管道。不过ASP.NET Core源码远远不止这些,每个模块的实现较复杂,还有其他必不可少的模块(依赖注入、日志系统、异常处理等),需要更加深入的学习。我也会记录我的学习记录,最后来一张完整的Http请求管道图。

 

asp.net项目结构 asp.net core架构_ASP_09