gpt4 book ai didi

c# - 查询字符串的正确编码是什么?

转载 作者:太空狗 更新时间:2023-10-29 19:26:49 25 4
gpt4 key购买 nike

我正在尝试从 asp.net 应用程序向“http://mysite.dk/tværs?test=æ”这样的 url 发送请求,但我无法正确编码查询字符串。或者可能查询字符串编码正确,我连接的服务无法正确理解它。

我尝试使用不同的浏览器发送请求并记录它们如何使用 Wireshark 对请求进行编码,我得到了这些结果:

Firefox: http://mysite.dk/tv%C3%A6rs?test=%E6Ie8:     http://mysite.dk/tv%C3%A6rs?test=\xe6Curl:    http://mysite.dk/tv\xe6rs?test=\xe6

Both Firefox, IE and Curl receive the correct results from the service. Note that they encode the danish special character 'æ' differently in the querystring.

When I send the request from my asp.net application using HttpWebRequest, the URL gets encoded this way:

http://mysite.dk/tv%C3%A6rs?test=%C3%A6

It encodes the querystring the same way as the path part of the url. The remote service does not understand this encoding, so I don't get a correct answer.

For the record, 'æ' (U+00E6) is %E6 in ISO-LATIN-1, and %C3%A6 in UTF-8.

I could change the remote service to accept the UTF-8 encoded querystring, but then the service would stop working in browsers and I am not really interested in that. Is there a way to specify to .NET that it shouldn't encode querystrings with UTF-8?

I am creating the webrequest like this:

var req = WebRequest.Create("http://mysite.dk/tværs?test=æ") as HttpWebRequest;

但问题似乎源自 System.Uri,它显然在 WebRequest.Create 中使用:

var uri = new Uri("http://mysite.dk/tværs?test=æ");
// now uri.AbsolutePath == "http://mysite.dk/tv%C3%A6rs?test=%C3%A6"

最佳答案

看起来您正在对整个 URL 应用 UrlEncode - 这是不正确的,路径和查询字符串的编码方式与您所见的不同。 URI WebRequest 的编码是做什么的?

您可以使用 UriBuilder 手动构建各个部分,或使用 UrlPathEncode 手动编码对于路径和 UrlEncode用于查询字符串名称和值。

编辑:

如果问题出在路径上,而不是查询字符串上,您可以尝试打开 IRI support , 通过 web.config

<configuration>
<uri>
<iriParsing enabled="true" />
</uri>
</configuration>

那应该在路径中单独留下国际字符。

关于c# - 查询字符串的正确编码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5979713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com