ASP.NET核心中间件中Map和MapWhen分支之间的区别? [英] difference between Map and MapWhen branch in asp.net core Middleware?

查看:303
本文介绍了ASP.NET核心中间件中Map和MapWhen分支之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在验证请求时何时在asp.net核心中间件中使用Map和MapWhen分支.

When to use Map and MapWhen branch in asp.net core middleware while we are authenticating request.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Map("", (appBuilder) =>
    {
        appBuilder.Run(async (context) => {
            await context.Response.WriteAsync("");
        });
    });

    app.MapWhen(context => context.Request.Query.ContainsKey(""), (appBuilder) =>
    {
        appBuilder.Run(async (context) =>
        {
            await context.Response.WriteAsync("");
        });

    });
}

推荐答案

Map只能基于指定请求路径的匹配来分支请求. MapWhen功能更强大,并允许基于与当前HttpContext对象一起操作的指定谓词的结果分支请求. 到目前为止,HttpContext包含有关HTTP请求的所有信息,MapWhen允许您使用非常特定的条件来分支请求管道.

Map could branch the request based on match of the specified request path only. MapWhen is more powerful and allows branching the request based on result of specified predicate that operates with current HttpContext object. As far HttpContext contains all information about HTTP request, MapWhen allows you to use very specific conditions for branching request pipeline.

任何Map调用都可以轻松转换为MapWhen,反之亦然.例如,此Map调用:

Any Map call could be easily converted to MapWhen, but not vice versa. For example this Map call:

app.Map("SomePathMatch", (appBuilder) =>
{
    appBuilder.Run(async (context) => {

        await context.Response.WriteAsync("");
    });
});

等效于以下MapWhen调用:

app.MapWhen(context => context.Request.Path.StartsWithSegments("SomePathMatch"), (appBuilder) =>
{
    appBuilder.Run(async (context) =>
    {
        await context.Response.WriteAsync("");
    });
});

因此回答您的问题何时使用Map和MapWhen分支":仅基于请求路径分支请求时,请使用Map.当基于HTTP请求中的其他数据分支请求时,请使用MapWhen.

So answering your question "When to use Map and MapWhen branch": use Map when you branch request based on request path only. Use MapWhen when you branch request based on other data from the HTTP request.

这篇关于ASP.NET核心中间件中Map和MapWhen分支之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆