【问题标题】:decode querystring within context.Request在 context.Request 中解码查询字符串
【发布时间】:2012-09-07 20:10:46
【问题描述】:

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

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

所以例如而不是得到

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

我明白了

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

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

我猜查询字符串中的第二个键是 amp;root 即 & 符号之后的部分。

我想知道是否有办法在服务器端自动对查询字符串进行 html 和 urldecode,这样程序就不会混淆。

【问题讨论】:

  • 你用C标记了这个问题——你的意思是C#吗?
  • 不应该是:context.Request.QueryString["root"]字符串 root
  • yes.. 我的意思是 c#... context.Request.QueryString["root"] 应该返回 small 但它返回 null 因为没有 root 这样的键...。根

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


【解决方案1】:

多次致电HttpUtility.HtmlDecodeHttpUtility.UrlDecode 并没有什么坏处。

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

【讨论】:

  • 谢谢...我实际上是在尝试避免那样做...但我想因为在解码后无法设置 context.Request.QueryString,这也应该有效。想知道是否有办法在服务器端对其进行解码,以便我可以将程序排除在外
  • 其实,如果你的原始网址中有一个编码+号,你调用了两次解码,这不是问题吗?第一次,它将被解码为 +,但第二次,+ 将被解码为空格。除非我错过了什么?
  • @rar 发布一个使用 for ex HttpUtility.UrlEncodeHttpUtility.UrlDecode 的示例,我们可以讨论具体的示例代码。
【解决方案2】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    相关资源
    最近更新 更多