Asp.Net Core middleware pathstring startswithsegments issue

冷暖自知 提交于 2019-12-07 04:27:49

问题


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("/")
);

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?


回答1:


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


来源:https://stackoverflow.com/questions/49692922/asp-net-core-middleware-pathstring-startswithsegments-issue

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