首页 新闻 赞助 找找看

ASP.NET Core: app.Map如何匹配根路径

0
悬赏园豆:50 [已解决问题] 解决于 2016-08-10 18:19

请问在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)

dudu的主页 dudu | 高人七级 | 园豆:31075
提问于:2016-08-09 14:16
< >
分享
最佳答案
1

之前错误理解了app.Map的用途,正确的解决方法是:

app.Use((context, next) =>
{
    if (context.Request.Path == "/")
    {
        context.Response.Redirect("/markdown/tohtml");
        return Task.FromResult(0);
    }
    return next();
}); 
dudu | 高人七级 |园豆:31075 | 2016-08-09 17:24
其他回答(4)
0

~/markdown/ToHtml

???

没在Linux下用过asp.net,但win下的路径,站点根路径都是这样写吧?

收获园豆:10
顾晓北 | 园豆:10844 (专家六级) | 2016-08-09 14:18

"/markdown/ToHtml"这样写没问题,我问的是app.Map(""中的匹配规则该如何写?

支持(0) 反对(0) dudu | 园豆:31075 (高人七级) | 2016-08-09 14:20
0

这应该是个bug吧。

收获园豆:10
CodeHsu | 园豆:5468 (大侠五级) | 2016-08-09 15:00
0

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开头的路径会被匹配,所以应该是不能办到只匹配根路径的吧。

收获园豆:10
ArthurLi | 园豆:686 (小虾三级) | 2016-08-09 15:06
0

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.

收获园豆:10
小熊vs | 园豆:20 (初学一级) | 2016-08-09 15:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册