Asp.Net Core middleware pathstring startswithsegments issue

こ雲淡風輕ζ 提交于 2019-12-05 10:54:52

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();
}

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

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!