解码context.Request中的查询字符串

时间:2012-09-07 20:10:46

标签: c# asp.net .net windows-server-2008

我有一个ashx文件,需要一些查询字符串值才能提供合适的图像。

问题是一些搜索引擎urlencode然后htmlencode这些网址在他们的缓存中或当他们索引那些。

例如,而不是获得

/preview.ashx?file=abcd.jpg&root=small

我得到了

/preview.ashx?file=abcd.jpg&root=small

这基本上抛弃了context.Request.QueryString["root"]所以它认为没有变量 root

我想查询字符串中的第二个键是 amp; root ,即&登录。

我想知道的是,是否有办法在服务器端自动html和urldecode查询字符串,以便程序不会混淆。

2 个答案:

答案 0 :(得分:7)

不止一次致电HttpUtility.HtmlDecodeHttpUtility.UrlDecode毫无害处。

string queryString = "/preview.ashx?file=abcd.jpg&root=small";
var parsedString = HttpUtility.HtmlDecode(queryString);
var root = HttpUtility.ParseQueryString(parsedString)["root"];

答案 1 :(得分:4)

要进行URL编码和解码,您可以使用以下方法:

string encoded = System.Web.HttpUtility.UrlEncode(url);

string decoded = System.Web.HttpUtility.UrlDecode(url);

我见过过去查询字符串被双重编码的实例。在这种情况下,您需要进行双重解码 - 这可能是您的问题......