How can I send a GET request containing a colon, to an ASP.NET MVC2 controller?

一个人想着一个人 提交于 2019-12-06 05:12:17

问题


This works fine:

GET /mvc/Movies/TitleIncludes/Lara%20Croft

When I submit a request that contains a colon, like this:

GET /mvc/Movies/TitleIncludes/Lara%20Croft:%20Tomb

...it generates a 400 error. The error says ASP.NET detected invalid characters in the URL.

If I try url-escaping, the request looks like this:

GET /mvc/Movies/TitleIncludes/Lara%20Croft%3A%20Tomb

...and this also gives me a 400 error.

If I replace the colon with a | :

GET /mvc/Movies/TitleIncludes/Lara%20Croft|%20Tomb

..that was also rejeted as illegal, this time with a 500 error. The message: Illegal characters in path.

URL-escaping that | results in the same error.


I really, really don't want to use a querystring parameter.


related:
Sending URLs/paths to ASP.NET MVC controller actions


回答1:


I found that URL encoding did not work, but custom encoding did.
I guess ASPNET MVC uses the filesystem to do the parsing and routing, because a character in the URL that is not legal in the filesystem, causes a 500 or 400 error.

So what I did was replace colons with the unicode ¡ character in the javascript side, and then do the converse in the action. like this:

browser:

function myEscape(s){
    return s.replace(':', '%C2%A1').trim();
}

in the action, call this conversion before using the argument:

private string MyCustomUnescape(string arg)
{
    return arg.Replace("¡", ":");
}

The same approach works for slashes - just pick a different unicode character. Of course if your string arguments themselves are unicode, then you'll have to use non-printable characters for the "encoded" forms.




回答2:


If SEO is not a problem you may use base64 and then urlencode that. After the first step every character you'll have will be easily encoded. Decoding in .NET is as easy as using the helper in System.Web.HttpUtility and System.Convert.




回答3:


Similar answered here: https://stackoverflow.com/a/12037000/134761

Use question mark and ampersands for arguments and URL encode the arguments.

Example: GET /mvc/Movies/TitleIncludes?title=Lara%20Croft%3A%20Tomb

I agree it would be nice to encode things into the url as well, but there is probably a good reason not to.



来源:https://stackoverflow.com/questions/2593156/how-can-i-send-a-get-request-containing-a-colon-to-an-asp-net-mvc2-controller

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