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