请问在ASP.NET Core中用app.Map如何匹配根路径(/)?
如果用空字符串,会匹配所有url,比如下面的代码:
app.Map("", _ =>
{
_.Run((context) =>
{
context.Response.Redirect("/markdown/ToHtml");
return Task.FromResult(0);
});
});
不管访问什么url,都会被重定向,结果引起浏览器报错“redirected you too many times.”
app.Map() 的实现代码见MapExtensions.cs
如果使用app.Map("/"),会出现下面的异常:
Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The path must not end with a '/'
Parameter name: pathMatch
at Microsoft.AspNetCore.Builder.MapExtensions.Map(IApplicationBuilder app, PathString pathMatch, Action`1 configuration)
之前错误理解了app.Map的用途,正确的解决方法是:
app.Use((context, next) =>
{
if (context.Request.Path == "/")
{
context.Response.Redirect("/markdown/tohtml");
return Task.FromResult(0);
}
return next();
});
~/markdown/ToHtml
???
没在Linux下用过asp.net,但win下的路径,站点根路径都是这样写吧?
"/markdown/ToHtml"这样写没问题,我问的是app.Map(""
中的匹配规则该如何写?
这应该是个bug吧。
Branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.
方法注释是这样的,以指定path开头的路径会被匹配,所以应该是不能办到只匹配根路径的吧。
Branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.