Howto allow “Illegal characters in path”?

一个人想着一个人 提交于 2019-12-28 04:01:07

问题


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

routes.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?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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".



来源:https://stackoverflow.com/questions/2087246/howto-allow-illegal-characters-in-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!