C#ASP.NET HttpWebRequest自动解码查询字符串中的符号(&;)值?

C#ASP.NET HttpWebRequest自动解码查询字符串中的符号(&;)值?,c#,asp.net,query-string,decode,ampersand,C#,Asp.net,Query String,Decode,Ampersand,假设以下Url: "http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents & Functions + Properties.docx&Save=true" "http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents%20%26%20Functions%20%2B%20Pro

假设以下Url:

"http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents & Functions + Properties.docx&Save=true"
"http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents%20%26%20Functions%20%2B%20Properties.docx&Save=true"
我使用HttpUtility.UrlEncode()对Filename参数的值进行编码,并创建以下Url:

"http://server/application1/TestFile.aspx?Library=Testing&Filename=Documents & Functions + Properties.docx&Save=true"
"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)


我无法正确读取参数Filename的值。我缺少什么吗?

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


您需要编写
Request.QueryString[“FileName”]

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

多年后我回答这个问题,因为我遇到了这个问题并找到了解决方案。问题在于
HttpRequest.Url
实际上不是您给出的值
HttpRequest.Url
是一个
Uri
类,该值是该类的
ToString()
ToString()解码Url。相反,您要使用的是
HttpRequest.Url.OriginalString
。这是您正在查找的URL的编码版本。希望这能帮助将来遇到这个问题的人。

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

解决此问题的两个变通方法:

  • 在服务器上实现自己的查询字符串解析。这不好玩,但很有效
  • 双编码与。首先只对字符串中的符号进行编码,然后对整个字符串进行编码。(这是一个简单的解决方案,但不可扩展,因为它会给客户端带来负担。)

  • 它返回:Documents(Value-after&was-missing)如果我不使用UrlEncode并将其原始发送,比如“&Functions+Properties.docx&Save=true”,那么在服务器上,我前面提到的变量具有相同的值。因此,无论我是否使用UrlEncode,我在服务器上都会得到相同的结果。无论如何,我找到了一个解决方案,我用我的自定义编码器/解码器手动编码文件名的值,效果很好。