Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC removes double forward slashes from request parameters

In my ASP.NET MVC 4 application I have an action on controller that gets URL string as a parameter:

public ActionResult Get(string url)
{
    var hash = TextUtil.GenerateShortStringHash(url);
    ...
    return Content(html, "text/html");
}

The request looks like this: http://localhost:37779/api/get/http:%2F%2Fwww.mysite.com But on some level application automatically replaces double slashes with single one.

enter image description here

Where does this happen? Is there any way to prevent such behavior? Thanks.

like image 841
yshchohaleu Avatar asked Mar 03 '14 16:03

yshchohaleu


2 Answers

My suspicion is that because it's part of the hierarchical portion of the URL it's automatically converting the double slashes to a single slash because double slashes aren't allowed in that portion of the URL. Because URLs contain characters that aren't allowed in the hierarchical portion of the URL, it's best to specify it (suitably encoded) as part of the query string (if a GET request) or in the form parameters (for a POST).

http://localhost:37779/api/get/?url=http:%2F%2Fwww.mysite.com
like image 157
tvanfosson Avatar answered Oct 13 '22 19:10

tvanfosson


I completely agree with @tvanfosson that such special characters should be passed as a query string parameter instead of using the path portion of the url. Scott Hanselman wrote a nice blog post explaining the challenges you will face if you attempt to pass such characters.

This being said, you could make it work using double encoding:

http://localhost:37779/api/get/http%253A%252F%252Fwww.mysite.com

and in your controller action:

public ActionResult Get(string url)
{
    var hash = TextUtil.GenerateShortStringHash(HttpUtility.UrlDecode(url));
    ...
    return Content(html, "text/html");
}

In order for this to work you need to add the following to your web.config to enable double encoding:

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

and also explicitly define the invalid characters so that : and / are not part of them or you will get 400 Bad Request:

<system.web>
    <httpRuntime requestPathInvalidCharacters="&lt;,&gt;" />
</system.web>
like image 28
Darin Dimitrov Avatar answered Oct 13 '22 18:10

Darin Dimitrov