ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Asp.net Core 中间件总结

2022-07-11 21:32:14  阅读:170  来源: 互联网

标签:Core RequestDelegate app 中间件 next context net builder


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

1.RequestDelegate

  • RequestDelegate委托对象作为参数调用了WebApplication对象的Run扩展方法。
  • 该扩展方法只是注册了一个中间件,具体点,就是说这个扩展方法用于注册处于管道末端的中间件

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

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!");


  • 其实很少会将中间件定义为上面的这三种形式,其中一种最直接的实现就是实现“ IMiddleware ”接口,它可以将依赖注入功能结合在一起,实现“ IMiddleware ”的类中可以注入服务

2.实现IMiddleware接口实现

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

  

 

 

3.按照约定实现中间件

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

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

  

 

  

 

 

 

  

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有