编程语言
首页 > 编程语言> > Asp.net Core 中间件总结

Asp.net Core 中间件总结

作者:互联网

《ASP.NET Core 6 框架解密》 总结,笔记:

1.RequestDelegate

  如下图,主要是几种委托的写法。

RequestDelegate handler = context => context.Response.WriteAsync("Hello,World!");
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.Run(handler);
app.Run();
var app = WebApplication.Create(args);
IApplicationBuilder builder = app;
builder.Use(HelloMiddleware)
    .Use(WorldMiddleware);
app.Run();

static RequestDelegate HelloMiddleware(RequestDelegate next) =>
    async httpcontext =>
    {
        await httpcontext.Response.WriteAsync("Hello,");
        await next(httpcontext);
    };

static RequestDelegate WorldMiddleware(RequestDelegate next) =>
    httpcontext => httpcontext.Response.WriteAsync("World!");
var app = WebApplication.Create(args);
IApplicationBuilder builder = app;
builder.Use(HelloMiddleware)
    .Use(WorldMiddleware);
app.Run();

//Func<HttpContext,RequestDelegate,Task>
//Func<HttpContext,Func<Task>,Task>
static async Task HelloMiddleware(HttpContext context, RequestDelegate next)
{
    await context.Response.WriteAsync("Hello,");
    await next(context);
}

static Task WorldMiddleware(HttpContext context, RequestDelegate next) =>
    context.Response.WriteAsync("World!");


2.实现IMiddleware接口实现

  这个比较简单,实现IMiddleware接口,如何注册成单利,实现类中可以注入相关服务。

  

 

 

3.按照约定实现中间件

  第一次知道中间件还可以按约定实现。

  例子比较简单,看一遍就明白了:

  

 

  

 

 

 

  

标签:Core,RequestDelegate,app,中间件,next,context,net,builder
来源: https://www.cnblogs.com/youlicc/p/16464404.html