加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

aspnetcore的中间件

发布时间:2020-12-16 07:20:09 所属栏目:asp.Net 来源:网络整理
导读:Run会终止中间件继续传递 1 app.Run( new RequestDelegate( async context = 2 { 3 await Task.Run(() = 4 { 5 context.Response.WriteAsync( " 被Run截取到了 " ); 6 }); 7 })); 8 9 app.Run( new RequestDelegate( async context = 10 { 11 await context.

Run会终止中间件继续传递

 1 app.Run(new RequestDelegate(async context =>
 2 {
 3         await Task.Run(() =>
 4         {
 5                 context.Response.WriteAsync("被Run截取到了");
 6          });
 7 }));
 8 
 9 app.Run(new RequestDelegate(async context =>
10 {
11         await context.Response.WriteAsync("被Run截取到了");
12 }));

?Use 会继续传递

app.Use(async (context,next) =>
{
        context.Response.Headers.Add("ResponseAt",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff"));
        await next();
});

Map和MapWhen

app.Map("/Test",configuration =>
            {
                configuration.Run(async context =>
                {
                    await context.Response.WriteAsync("Test被截取了");
                });
            });

            app.MapWhen(
                context => context.Request.Path.Value.Contains("Test",StringComparison.CurrentCultureIgnoreCase),configuration => configuration.Run(async context =>
                {
                    await context.Response.WriteAsync("带Test的被截取了");
                }));

使用UseMiddleware

public class MyMiddleware
    {
        private readonly RequestDelegate _next;

        private readonly ILogger _logger;

        private readonly string _prefix;

        public MyMiddleware(RequestDelegate next,ILoggerFactory factory,string prefix)
        {
            _next = next;
            _logger = factory.CreateLogger<MyMiddleware>();
            _prefix = prefix;
        }


        public async Task Invoke(HttpContext context)
        {
            _logger.LogInformation("" + _prefix + "" + context.Request.Path.Value);
            context.Response.Headers.Add("ResponseAt",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff"));
            await _next(context);
        }
    }
app.UseMiddleware<MyMiddleware>("博客");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读