ToB企服应用市场:ToB评测及商务社交产业平台

标题: .Net Core 管道底层源码实现 [打印本页]

作者: 耶耶耶耶耶    时间: 2025-1-14 13:37
标题: .Net Core 管道底层源码实现
在 .NET Core 中,请求处理管道是一个中间件(Middleware)链,用于处理 HTTP 请求并天生响应。管道的底层实现基于 Microsoft.AspNetCore.Http 定名空间中的一些核心类和接口
1. 核心组件

1.1 HttpContext

1.2 HttpRequest 和 HttpResponse

1.3 RequestDelegate

  1. public delegate Task RequestDelegate(HttpContext context);
复制代码
1.4 Middleware

2. 定义 ApplicationBuilder 接口

首先,我们定义 IApplicationBuilder 接口:
  1. public interface IApplicationBuilder
  2. {
  3.     // 添加中间件到管道中
  4.     IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
  5.     // 构建最终的请求处理管道
  6.     RequestDelegate Build();
  7.     // 获取或设置应用程序服务提供者
  8.     IServiceProvider ApplicationServices { get; set; }
  9.     // 获取属性字典,用于存储共享数据
  10.     IDictionary<string, object> Properties { get; }
  11. }
复制代码
3. 定义 RequestDelegate 委托

管道的核心是基于委托(Delegate)和上下文(Context)的机制。
**RequestDelegate**:是一个表现处理 HTTP 请求的委托。
  1. public delegate Task RequestDelegate(HttpContext context);
复制代码
每个中间件本质上是一个 RequestDelegate,它接收 HttpContext 并处理请求,同时可以选择调用下一个中间件。
4. 实现 ApplicationBuilder 类

接下来,我们实现 ApplicationBuilder 类:
  1. public class ApplicationBuilder : IApplicationBuilder
  2. {
  3.     // 存储中间件组件的列表
  4.     private readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>();
  5.     // 获取或设置应用程序服务提供者
  6.     public IServiceProvider ApplicationServices { get; set; }
  7.     // 获取属性字典,用于存储共享数据
  8.     public IDictionary<string, object> Properties { get; } = new Dictionary<string, object>();
  9.     // 添加中间件到管道中
  10.     public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
  11.     {
  12.         _components.Add(middleware);
  13.         return this;
  14.     }
  15.     // 构建最终的请求处理管道
  16.     public RequestDelegate Build()
  17.     {
  18.         // 默认的请求处理程序,返回 404 状态码
  19.         RequestDelegate app = context =>
  20.         {
  21.             context.Response.StatusCode = 404;
  22.             return Task.CompletedTask;
  23.         };
  24.         // 反向遍历中间件组件列表,构建嵌套的请求处理管道
  25.         foreach (var component in _components.Reverse())
  26.         {
  27.             app = component(app);
  28.         }
  29.         return app;
  30.     }
  31. }
复制代码
5. 创建中间件

我们创建一个简单的日志网络中间件来展示如何使用 **ApplicationBuilder** :
  1. public class CustomizeMiddleware
  2. {
  3.     private readonly RequestDelegate _next;
  4.     // 构造函数,接受下一个中间件的委托
  5.     public CustomizeMiddleware(RequestDelegate next)
  6.     {
  7.         _next = next;
  8.     }
  9.     // 中间件的请求处理方法
  10.     public async Task Invoke(HttpContext context)
  11.     {
  12.         Console.WriteLine("自定义中间件: Before");
  13.         await _next(context); // 调用下一个中间件
  14.         Console.WriteLine("自定义中间件: After");
  15.     }
  16. }
复制代码
6. 使用 ApplicationBuilder 构建管道
  1. public class Program
  2. {
  3.     public static void Main(string[] args)
  4.     {
  5.         // 创建 ApplicationBuilder 实例
  6.         var builder = new ApplicationBuilder();
  7.         // 添加 CustomizeMiddleware 到管道中
  8.         builder.Use(next => new CustomizeMiddleware(next).Invoke);
  9.         // 添加内联中间件到管道中
  10.         builder.Use(next => async context =>
  11.         {
  12.             Console.WriteLine("内联中间件: Before");
  13.             await next(context); // 调用下一个中间件
  14.             Console.WriteLine("内联中间件: After");
  15.         });
  16.         // 构建最终的请求处理管道
  17.         var app = builder.Build();
  18.         // 创建一个 HttpContext 实例
  19.         var context = new DefaultHttpContext();
  20.         // 执行管道
  21.         app(context).Wait();
  22.     }
  23. }
复制代码
输入效果为:

7.总结

.NET Core 管道的底层实现是基于委托链的机制,每个中间件都是一个 RequestDelegate,通过链式调用来处理 HTTP 请求和响应。管道的构建过程通过 IApplicationBuilder 接口完成,中间件的添加次序决定了管道的执行次序。通过明白管道的底层实现,可以更好地掌握 .NET Core 的请求处理机制,并能够机动地配置和扩展管道。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4