如何处理httplistenerrequest中编码的URL?
-
10-10-2019 - |
题
我正在构建一个简单的服务器 HttpListener
处理请求。我发送给其的查询字符串参数如有必要时进行URL编码。例如,发送汉字字符串 "尺八"
, ,编码是 "%E5%B0%BA%E5%85%AB"
.
我的样本URL,那是 "/?q=%E5%B0%BA%E5%85%AB"
.
在我的上下文回调中,我有:
HttpListenerContext context = Listener.EndGetContext();
string rawUrl = context.Request.RawUrl;
string query = context.Request.QueryString["q"];
检查结果,我得到:
rawUrl = "/?q=%E5%B0%BA%E5%85%AB"
query = "尺八"
但是如果我看着 context.Request.Url
, ,我明白了 {http://localhost:8080/?q=尺八}
.
看起来像是查询字符串 context.Request.QueryString
使用UTF-8以外的一些编码进行解码。
我的解决方法是忽略 context.Request.QueryString
并通过这样做来创建我自己的东西:
var queryString = HttpUtility.ParseQueryString(context.Request.Url.Query);
这给了我正确的价值,但这似乎是一个黑客。
有什么办法告诉 HttpListener
(或上下文或请求)将查询字符串解释为UTF-8,我认为这是标准的吗?还是我应该忍受这个解决方法?
解决方案
通过查看代码,它依赖于将UTF8设置为utf8的contencododing。这是httplistenerrequest的Querystring属性的狙击:
public NameValueCollection QueryString
{
get
{
NameValueCollection nvc = new NameValueCollection();
Helpers.FillFromString(nvc, this.Url.Query, true, this.ContentEncoding);
return nvc;
}
}
由于无法修改与“ hack'”所困扰的contencOdoding属性。无论如何,我认为您对httputility.parsequerystring可能会为您提供最好的服务。
其他提示
尝试 System.Web.HttpUtility
string query = "d=bla bla bla";
string encoded = System.Web.HttpUtility.UrlEncode( query, System.Text.Encoding.UTF8 );
学到更多 https://msdn.microsoft.com/en-us/library/system.web.httputility(V=VS.110).aspx
不隶属于 StackOverflow