如何允许"路径中的非法字符"?

hbr*_*uce 18 asp.net-mvc routing

我有一个MVC.NET应用程序,其中一个路由如下:

routes.MapRoute("member", "member/{id}/{*name}", new { controller = "member", action = "Details", id = "" }, new { id = @"\d+" });

因此,链接可以是这样的:http:// domain/member/123/any_kind_of_username

这通常工作正常,但如果路径包含非法字符(例如双qoute:http:// domain/member/123/my_ "user"_name),我会收到"System.ArgumentException:路径中的非法字符".

经过大量谷歌搜索后,最好的建议似乎是确保网址不包含任何此类字符.不幸的是,在这种情况下,这是我无法控制的.

有办法解决这个问题吗?

bka*_*aid 9

斯科特汉塞尔曼发布了关于在路径中允许非法角色的一个很好的总结.

如果您确实想要允许受限制的字符,请通过编辑web.config将其从列表中删除(这可能仅适用于.NET 4和IIS7):

<system.web>
    <httpRuntime requestValidationMode="2.0" relaxedUrlToFileSystemMapping="true" requestPathInvalidCharacters="&lt;,&gt;,*,%,:,&amp;,\" />
</system.web>
Run Code Online (Sandbox Code Playgroud)

您可能还需要像hbruce建议的那样做:

<system.webServer>
    <security>
        <requestFiltering allowDoubleEscaping="true"/>
    </security>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

仍然有一些不起作用的特定路径(例如/ search /%),因为您将收到400"Bad Request - Invalid URL"消息.我发现的唯一解决方法是使用该部分作为查询字符串:/ search?q =%,具有上述步骤.


Vin*_*ren 0

您应该在提交之前在客户端对 URL 进行 URL 编码。尝试使用UrlHelper.Encode方法。

  • 即使从客户端发送编码的 URI,我也得到了这一点 (3认同)