3

假设以下网址:

"http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents & Functions + Properties.docx&Save=true"

我使用 HttpUtility.UrlEncode() 对 Filename 参数的值进行编码,并创建以下 Url:

"http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents%20%26%20Functions%20%2B%20Properties.docx&Save=true"

我将以下请求(编码版本)从客户端发送到 C# Web 应用程序。在服务器上,当我处理请求时,我遇到了问题。HttpRequest 变量包含部分解码的查询字符串。也就是说,当我尝试使用或快速查看 HttpRequest 的以下属性时,它们具有以下值。

Property = Value
================
HttpRequest.QueryString = "{Library=Testing&Filename=Documents+&+Functions+++Properties.docx&Save=true}"

HttpRequest.Url = "{http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents & Functions + Properties.docx&Save=true}"

HttpRequest.Url.AbsoluteUri = "http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents%20&%20Functions%20+%20Properties.docx&Save=true"

我还检查了以下属性,但它们都解码了 & 值。然而,所有其他值都保持正确编码(例如空格是 %20)。

HttpRequest.Url.OriginalString

HttpRequest.Url.Query

HttpRequest.Url.PathAndQuery

HttpRequest.RawUrl

我无法正确读取参数 Filename 的值。我错过了什么吗?

4

4 回答 4

2

QueryString属性返回一个NameValueCollection对象,该对象将查询字符串键映射到完全解码的值。

你需要写Request.QueryString["FileName"]

于 2010-09-08T12:55:44.330 回答
2

多年后我才回答这个问题,因为我刚刚遇到这个问题并找到了解决方案。问题是这HttpRequest.Url并不是你给出的真正价值。HttpRequest.Url是一个Uri类,该值是ToString()该类的值。ToString()对于 Uri 类解码 Url。相反,您要使用的是HttpRequest.Url.OriginalString. 那是您要查找的 URL 的编码版本。希望这可以帮助一些未来遇到这个问题的人。

于 2012-02-15T18:59:29.197 回答
1

不使用 UrlEncode 时会发生什么?您没有显示您如何准确地使用使用 UrlEncode 创建的 url,因此很可能只是对事物进行了双重编码(许多框架会自动为您编码 URL)。

于 2010-09-08T13:51:06.767 回答
0

FWIW 我在使用 RavenDB(版本 960)时遇到了同样的问题。他们实现了自己的 HttpRequest 对象,其行为就像这样——它首先只解码 & 符号(从%26to &),然后解码整个值。我相信这是一个错误。

这个问题的几个解决方法:

  1. 在服务器上实现您自己的查询字符串解析。这不好玩,但很有效。
  2. 双重编码 & 符号。首先只对字符串中的 & 符号进行编码,然后对整个字符串进行编码。(这是一个简单的解决方案,但不可扩展,因为它给客户端增加了负担。)
于 2012-09-13T18:18:24.223 回答