时间:2025-01-11 15:36
人气:
作者:admin
在 .NET Core 中,中间件(Middleware) 是处理 HTTP 请求和响应的核心组件。它们被组织成一个请求处理管道,每个中间件都可以在请求到达最终处理程序之前或之后执行操作。中间件可以用于实现各种功能,如身份验证、路由、日志记录、异常处理、静态文件服务等。
中间件是 HTTP 请求管道中的一个处理单元,负责处理传入的 HTTP 请求和返回的 HTTP 响应。每个中间件都有以下职责:
中间件的工作原理可以概括为以下几个步骤:
Func<RequestDelegate, RequestDelegate> 委托,或者是一个实现了 IMiddleware 接口的类。RequestDelegate 是一个表示处理 HTTP 请求的委托,它接收一个 HttpContext 对象并返回一个 Task。next(context))。next(context),那么请求将继续传递到下一个中间件。以下是一些常见的中间件及其工作原理:
HttpContext.User 中。示例:
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication(); // 启用身份验证
app.UseAuthorization(); // 启用授权
}
UseRouting 和 UseEndpoints 配置。示例:
public void Configure(IApplicationBuilder app)
{
app.UseRouting(); // 启用路由解析
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
wwwroot 目录下的文件),则直接返回文件内容。示例:
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles(); // 启用静态文件服务
}
示例:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage(); // 开发环境:显示详细错误页面
}
else
{
app.UseExceptionHandler("/Home/Error"); // 生产环境:重定向到错误页面
}
}
示例:
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<LoggingMiddleware> _logger;
public LoggingMiddleware(RequestDelegate next, ILogger<LoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
_logger.LogInformation($"Request: {context.Request.Method} {context.Request.Path}");
await _next(context);
_logger.LogInformation($"Response: {context.Response.StatusCode}");
}
}
你可以创建自定义中间件来处理特定的需求。自定义中间件通常是一个类,它包含一个 Invoke 或 InvokeAsync 方法,该方法接收 HttpContext 和一个 RequestDelegate 参数。
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// 在调用下一个中间件之前执行的操作
await context.Response.WriteAsync("Custom Middleware: Before\n");
// 调用下一个中间件
await _next(context);
// 在调用下一个中间件之后执行的操作
await context.Response.WriteAsync("Custom Middleware: After\n");
}
}
然后在 Startup.cs 中使用这个中间件:
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<CustomMiddleware>();
// 其他中间件
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
通过理解中间件的工作原理和常见应用场景,你可以更好地设计和优化 .NET Core 应用程序的请求处理流程。

上一篇:ASmile ORM “蝇”量级数据库框架介绍及示例
下一篇:中间件 vs 过滤器
Microsoft Agent Framework Skills 执行 Scripts(实
EF Core 原生 SQL 实战:FromSql、SqlQuery 与对