.net5 中定义中间件
1.Startup.cs中 Configure 函数下添加app.Map
// “/api” 表示每个地址包含"/api"的方法都会执行这个中间件
app.Map("/api",async (Builder) =>
// Middleware 自定义中间件类
Builder.UseMiddleware<Middleware>();
});
- Middleware 自定义中间件类
public class Middleware
{
// 每一个自定义中间件类 必须有一个 RequestDelegate类型值
// 且返回类型必须是Task类型 且是异步函数 最后一步 next(coutext) 执行
private readonly RequestDelegate _next;
public Middleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Get请求 拿到pwd字段的值 并写入文件
string pwd = context.Request.Query["pwd"];
await System.IO.File.WriteAllTextAsync(@"D:/01.txt",pwd);
await _next(context);
}
}