问题
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