开发者

Howto allow "Illegal characters in path"?

I have a MVC.NET application with one route as follows:

r开发者_JAVA百科outes.MapRoute("member", "member/{id}/{*name}", new { controller = "member", action = "Details", id = "" }, new { id = @"\d+" });

Thus, a link could be something like this: http://domain/member/123/any_kind_of_username

This works fine in general but if the path contains illegal characters (e.g. a double qoute: http://domain/member/123/my_"user"_name) I get a "System.ArgumentException: Illegal characters in path."

After much googling the best suggestions seems to be to make sure that the url doesn't contain any such characters. Unfortunately, that is out of my control in this case.

Is there a way to work around this?


Scott Hanselman posted a good summary on allowing illegal characters in the path.

If you really want to allow characters that are restricted, remove them from the list by editing your web.config (this will probably only work in .NET 4 and on IIS7):

<system.web>
    <httpRuntime requestValidationMode="2.0" relaxedUrlToFileSystemMapping="true" requestPathInvalidCharacters="&lt;,&gt;,*,%,:,&amp;,\" />
</system.web>

You may also need to do as hbruce suggests:

<system.webServer>
    <security>
        <requestFiltering allowDoubleEscaping="true"/>
    </security>
</system.webServer>

There are still some certain paths that will not work, (such as /search/% ) as you will get the 400 "Bad Request - Invalid URL" message. The only workaround I've found is to use that part as a querystring: /search?q=% with the above steps.


Turns out you could avoid this by setting allowDoubleEscaping="false" in for requestFiltering in web.Config. I.e:

<configuration>
  <system.webServer>
    <security>
      <requestFiltering allowDoubleEscaping="false" />
    </security>
  </system.webServer>
</configuration>

Perhaps not the perfect solution (any suggestions for a better one is much appreciated), but it solves the problem.


You should URL-encode the URL at the client end before submitting it. Try using the UrlHelper.Encode method.


What about an ampersand (&) in the url? For example: mysite.com/JellyBeans/PB&J, where "PB&J" is a parameter value in a controller action method. How do you get around MVC and the ASP.NET engine from treating that as an illegal char in the base url string? Encoding that with a %26 doesn't appear to work. Odd thing, when launching VS debug the local web server (VS built in web server) handles that case fine (both as an & and a %26), but when deployed to a web server running IIS7 the url results in a "Bad Request".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜