
在ASP.NET Core应用开发中,Middleware(中间件)是构建请求处理管道的核心组件。它能够对HTTP请求和响应进行处理、转换等操作,极大地增强了应用的灵活性和扩展性。深入学习Middleware管道执行机制,有助于开发者优化请求处理流程、提高应用性能。
RequestDelegate代表请求处理委托,每个Middleware都封装为一个RequestDelegate。IApplicationBuilder用于构建应用程序的请求处理管道,通过Use方法添加Middleware。public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (middleware == null)
{
throw new ArgumentNullException(nameof(middleware));
}
return app.Use(next => middleware(next));
}Startup.Configure方法构建管道。Use方法链式调用,将各个Middleware按顺序添加到管道中。using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
// 自定义Middleware类
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
public LoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// 请求处理前记录日志
System.Console.WriteLine("Request started");
await _next(context);
// 请求处理后记录日志
System.Console.WriteLine("Request ended");
}
}
// 扩展方法用于在管道中使用该Middleware
public static class LoggingMiddlewareExtensions
{
public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LoggingMiddleware>();
}
}
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseLoggingMiddleware();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello, World!");
});
app.Run();
}
}LoggingMiddleware构造函数接收RequestDelegate,Invoke方法中先记录请求开始日志,调用_next(context)传递请求,处理完后记录请求结束日志。扩展方法UseLoggingMiddleware方便在Startup中使用该Middleware。using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("Authorization", out var token))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized: No token provided");
return;
}
// 简单模拟令牌验证
if (token != "valid-token")
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized: Invalid token");
return;
}
await _next(context);
}
}
public static class AuthenticationMiddlewareExtensions
{
public static IApplicationBuilder UseAuthenticationMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AuthenticationMiddleware>();
}
}
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseAuthenticationMiddleware();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Authenticated successfully");
});
app.Run();
}
}Invoke方法中先检查请求头是否有Authorization字段,若没有或令牌无效则返回401状态码并提示信息,否则调用_next(context)继续处理请求。Authorization字段或令牌无效,浏览器显示相应的未授权信息;若令牌有效,显示“Authenticated successfully”。// 假设这里业务Middleware在身份验证Middleware之前
app.Run(async (context) =>
{
await context.Response.WriteAsync("Some business logic");
});
app.UseAuthenticationMiddleware();app.UseAuthenticationMiddleware();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Some business logic");
});ASP.NET Core Middleware的管道执行机制是构建高效Web应用的关键。其核心要点在于理解请求在管道中的传递流程以及Middleware的模块化设计。适用场景广泛,包括各种Web应用的通用逻辑处理。未来在.NET新版本中,可能会进一步优化Middleware的性能和可扩展性,使开发者能更高效地构建复杂的Web应用。