NetCore中间件的一些知识
1.中间件的执行顺序为先进后出
2.NetCore内置的中间件有
Authentication: 提供身份验证支持
CORS: 配置跨域资源共享
Response Caching: 提供缓存响应支持
Response Compression: 提供响应压缩支持
Routing: 定义和约束请求路由
Session: 提供用户会话管理
Static Files: 为静态文件和目录浏览提供服务提供支持
URL Rewriting Middleware: 用于重写 Url,并将请求重定向的支持
3.编写中间件
①方式一(中间件写在Startup.cs中)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (context, next) =>
{
// TO DO
await next();
});
}
②方式二(中间件写在独立文件中)
中间件写法:
public class TestMiddleware
{
private readonly RequestDelegate _next;
public TestMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext)
{
// TO DO
return _next(httpContext);
}
}
注册到IApplicationBuilder:
public static class TestMiddlewareExtensions
{
public static IApplicationBuilder UseTestMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
}
在Startup中使用:
// Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseTestMiddleware();
}
补充:NetCore的学习地址https://docs.microsoft.com/zh-cn/aspnet/core/?view=aspnetcore-6.0