中间件是ASP.NET Core的一个基本组成部分。它允许你灵活且模块化地处理请求和响应。中间件会在请求流经应用程序的请求管道时对请求进行处理,在响应返回时也会对响应进行处理。
本文将阐释中间件、其用途以及如何在ASP.NET Core中创建自定义中间件。我们会使用通俗易懂的术语和示例来帮助理解。
中间件的示例包括:
管道中中间件的顺序很重要。较早添加的中间件可能会影响后续中间件的行为。
ASP.NET Core中的中间件与筛选器 《ASP.NET Core中的中间件与筛选器综合指南:含实际示例》 towardsdev.com
Program.cs
文件(旧版本中是Startup.cs
文件)中对其进行配置。以下是一个示例:app.Use(async (context, next) =>
{
Console.WriteLine("在调用下一个中间件之前");
await next();
Console.WriteLine("在调用下一个中间件之后");
});
app.Use(async (context, next) =>
{
Console.WriteLine("正在处理请求");
await context.Response.WriteAsync("你好,中间件!");
});
在这个示例中:
next()
之前和之后记录消息。如果一个中间件没有调用next()
,它就会截断管道,后续的中间件将不会再运行。
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
步骤1:创建中间件类 一个中间件类需要:
RequestDelegate
参数。InvokeAsync
方法来处理请求。以下是一个示例:
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// 预处理逻辑
Console.WriteLine("自定义中间件:在调用下一个之前");
// 调用管道中的下一个中间件
await _next(context);
// 后处理逻辑
Console.WriteLine("自定义中间件:在调用下一个之后");
}
}
步骤2:注册中间件 使用UseMiddleware
扩展方法在管道中注册中间件:
app.UseMiddleware<CustomMiddleware>();
app.Run(async (context) =>
{
await context.Response.WriteAsync("请求由终端中间件处理。");
});
app.Use(async (context, next) =>
{
Console.WriteLine("在Lambda中间件之前");
await next();
Console.WriteLine("在Lambda中间件之后");
});
这种方法对于执行简单任务很有用。
步骤1:创建中间件
public class TimingMiddleware
{
private readonly RequestDelegate _next;
public TimingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var startTime = DateTime.UtcNow;
await _next(context);
var endTime = DateTime.UtcNow;
var processingTime = endTime - startTime;
Console.WriteLine($"请求在{processingTime.TotalMilliseconds}毫秒内处理完成");
}
}
步骤2:注册中间件 将其添加到管道中,例如将以下代码添加到Program.cs
文件中:
app.UseMiddleware<TimingMiddleware>();
app.Run(async (context) =>
{
await context.Response.WriteAsync("请求已完成。");
});
当你运行应用程序时,控制台将显示每个请求所花费的时间。
app.UseAuthentication();
app.UseAuthorization();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
在这里,UseAuthentication
必须放在UseAuthorization
之前。否则,授权将会失败,因为用户尚未经过身份验证。
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
Console.WriteLine($"错误:{ex.Message}");
context.Response.StatusCode = 500;
await context.Response.WriteAsync("发生了一个错误。");
}
}
}
将其注册到管道中,以便全局捕获异常。
《.NET 6中的全局异常处理》 .NET 6中处理异常的一种有效方式 enlear.academy
中间件是ASP.NET Core的一项强大功能。它允许你自定义处理请求和响应的方式。你可以针对常见任务使用内置中间件,也可以针对特定需求创建自定义中间件。