Asp.Net Core中间件路径字符串startswithsegments问题 [英] Asp.Net Core middleware pathstring startswithsegments issue

查看:627
本文介绍了Asp.Net Core中间件路径字符串startswithsegments问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个Asp.NET Core 2.0应用程序,我想将不以/api开头的任何路径映射为仅重新执行到根路径.我添加了以下内容,但似乎不起作用:

Have a Asp.NET Core 2.0 application and I would like to map any path that does not start with /api to just reexecute to the root path. I added the below but doesn't seem to work:

app.MapWhen(
   c => !c.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase),
   a => a.UseStatusCodePagesWithReExecute("/")
);

不使用MapWhen()而仅使用app.UseStatusCodePagesWithReExecute("/")可以用于所有非root用户路径.只想为所有不是root且不是/api的路径添加过滤.有关如何执行此操作的任何想法?

Not using MapWhen() and just using app.UseStatusCodePagesWithReExecute("/") works for all paths not root. Just want to add filtering for all paths not root and not /api. Any ideas on how to do this?

推荐答案

分支管道在此处无法正常工作,因为您没有在状态代码页中间件之后添加MVC中间件.这是正确的管道设置:

Branched pipeline does not work correctly here because you have not added MVC middleware after status code page middleware. Here is the correct pipeline setup:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.MapWhen(
        c => !c.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase),
        a =>
        {
            a.UseStatusCodePagesWithReExecute("/");
            a.UseMvc();
        });

    app.UseMvc();
}

请注意,此处的中间件顺序很重要,您应该在MVC之前添加状态代码页中间件.

Note that middleware order matters here, you should add status code page middleware before MVC.

但是,在这里使用条件管道似乎有点过头了.您可以使用 URL重写中间件:

However using conditional pipeline seems like overkill here. You could achieve your goal with URL Rewriting Middleware:

var options = new RewriteOptions()
    .AddRewrite(@"^(?!/api)", "/", skipRemainingRules: true);
app.UseRewriter(options);

app.UseMvc();

这篇关于Asp.Net Core中间件路径字符串startswithsegments问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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