ASP.NET MVC parse URL query part
I want something to turn ?a=5&b=8
part of a URL into a dictionary { a:5, b:8 }.
Is there such method in .net or am I on my own?
I need to parse query part so that I can implement my own URL decoding. The problem is that Firefox uses different encoding (UTF8 or ISO-8859-1) depending on the used alphabet.
Example:
Firefox encodes as following:
- v v
http://localhost:8041/Reforge.aspx?name=ArcânisГ
Firefox turns into
http://localhost:8041/Reforge.as开发者_运维技巧px?name=Arc%C3%A2nis%D0%93`
Notice that UTF8
encoding is used for both non-ASCII characters.
- v
http://localhost:8041/Reforge.aspx?name=Arcâ
Firefox turns into
http://localhost:8041/Reforge.aspx?name=Arc%E2
Notice that ISO-8859-1
(Latin-1) encoding is used for the non-ASCII character.
Here is a related question: ASP.NET MVC does not understand mixed url encoding (UTF-8/Latin-1)
Request.QueryString is a NameValueCollection that is like a dictionary.
It can contain multiple values for the same key.
If "?a=5&b=8" not come from querystring you can use HttpUtility.ParseQueryString method to get a NameValueCollection
If you want a true dictionary:
var d = new Dictionary<String,Object>();
this.Request.QueryString.CopyTo(d);
Maybe a custom modelbinder to handle dictionaries? It seems like relying on the querystring, while perfectly valid, goes against the spirit of the framework. It also may make testing your action a little more difficult.
My first thought was that this was already handled by the default modelbinder facilites, but this doesn't appear to be the case. That said, I haven't tried it but this is where I'd start:
An Intuitive Dictionary Model Binder for ASPnet MVC
精彩评论