.Net Core 中间件与过滤器

过滤器这个是.Net MVC旧有的功能,中间件这个概念是新出的,

ASP.NET Core只是完成了HTTP请求调度、报文解析等必要的工作,像检查用户身份、设置缓存报文头等操作都是在中间件中完成中间件就是ASP.NET Core的一个组件,由前逻辑、next、后逻辑3部分组成,多个中间件组成一个管道,一个系统中可以有多个管道。ASP.NET Core执行的过程就是http请求和响应按照中间件组装的顺序在中间件之间流转的过程。

以前有封装过滤器进行用户身份检查、预处理请求数据,中间件的同样能完成,中间件的范围更广

cs 复制代码
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
//定义了对/test路径请求的处理,4-22为一个管道
app.Map("/test", async appbuilder => {
    //声明第一个中间件
    appbuilder.Use(async (context, next) => {
        context.Response.ContentType = "text/html";
        await context.Response.WriteAsync("1  Start<br/>");
        await next.Invoke();//执行下一个中间件
        await context.Response.WriteAsync("1  End<br/>");
    });
    //声明第二个中间件
    appbuilder.Use(async (context, next) => {
        await context.Response.WriteAsync("2  Start<br/>");
        await next.Invoke();
        await context.Response.WriteAsync("2  End<br/>");
    });
    //中间件执行完成后,执行run
    appbuilder.Run(async ctx => {
        await ctx.Response.WriteAsync("hello middleware <br/>");
    });
});
app.Run();
//注意,如果在中间件中使用ctx.Response.WriteAsync等方式向客户端发送响应,我们就不能
//再执行next.Invoke了把请求转到其他中间件了,因为其他中间件可能会对response进行了修改
//该案例仅仅当做演示
cs 复制代码
public class CheckAndParsingMiddleware
{
    private readonly RequestDelegate next;
    public CheckAndParsingMiddleware(RequestDelegate next)
    {
        this.next = next;
    }
	//中间件的前逻辑、next、后逻辑都在这里
    public async Task InvokeAsync(HttpContext context)
    {
        string pwd = context.Request.Query["password"];
        if (pwd=="123")
        {
            context.Items["BodyJson"] = "hellowrld";
            await next(context);//传递到下一个中间件
        }
        else
        {
            context.Response.StatusCode = 401;//不会传递到下一个中间件
        }
    }
}
cs 复制代码
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Map("/test", async appbuilder => {
    appbuilder.UseMiddleware<CheckAndParsingMiddleware>();//按注册顺序,执行中间件类的Invoke方法
    appbuilder.Run(async ctx => {
        Console.WriteLine("run start");
        ctx.Response.ContentType = "text/html";
        ctx.Response.StatusCode = 200;
        //HttpContext.Item在同一次请求中是共享的,用它来实现中间件之间数据的传递
        await ctx.Response.WriteAsync(ctx.Items["BodyJson"].ToString());
        Console.WriteLine("run end");
    });
});
app.Run();
相关推荐
lingggggaaaa7 小时前
小迪安全v2023学习笔记(七十九讲)—— 中间件安全&IIS&Apache&Tomcat&Nginx&CVE
笔记·学习·安全·web安全·网络安全·中间件·apache
利白16 小时前
iceoryx高性能进程间通信中间件,在Windows环境的编译教程
中间件·内存·进程通信·ipc·iceoryx
切糕师学AI17 小时前
如何建立针对 .NET Core web 程序的线程池的长期监控
java·前端·.netcore
小红帽2.01 天前
GOFLY开源客服系统-处理gin框架下的session中间件
中间件·gin
Ray Song1 天前
MCAP :机器人数据容器的全面实践指南
中间件·自动驾驶·dds·mcap
csdn_aspnet1 天前
使用 MongoDB.Driver 在 C# .NETCore 中实现 Mongo DB 过滤器
mongodb·c#·.netcore
Ray Song2 天前
【FastDDS】Layer Transport ( 05-Shared Memory Transport)
中间件·自动驾驶·dds·fastdds
北执南念2 天前
数据库中间件ShardingSphere v5.2.1
数据库·中间件
红鼻子时代2 天前
Day5-中间件与请求处理
中间件·fastapi·后端开发
tiancao2222 天前
安装3DS MAX 2026后,无法运行,提示缺少.net core的解决方案
.net·.netcore·3dsmax