gpt4 book ai didi

c# - 更改 HttpValueCollection 对参数进行编码的方式

转载 作者:可可西里 更新时间:2023-11-01 17:24:16 25 4
gpt4 key购买 nike

var original = "АБ";

var query = HttpUtility.ParseQueryString("");
query["Arg"] = original;
var tmp1 = query.ToString();

上面的代码(这是构建查询字符串的推荐方式)将参数编码为 Arg=%u0410%u0411
但是,目标 API 不接受此参数并要求以这种方式对其进行编码:Arg=%D0%90%D0%91
是否可以使 HttpValueCollection 使用此编码?

最佳答案

HttpValueCollection 的源代码中有注释解释了您的问题:

// DevDiv #762975: <form action> and other similar URLs are mangled since we use non-standard %uXXXX encoding.
// We need to use standard UTF8 encoding for modern browsers to understand the URLs.

https://referencesource.microsoft.com/#System.Web/HttpValueCollection.cs,9938b1dbd553e753,references

看起来这种行为可以通过 web.config 中的 appSetting 来控制。要获得您想要的行为,请添加:

<add key="aspnet:DontUsePercentUUrlEncoding" value="true" />

如果您的目标是 .NET 4.5.2+,则此值应默认设置为 true。

您可以在 FormUrlEncodedContent 中使用System.Net.Http 命名空间中的类。以下是如何执行此操作的示例:

string query;
using (var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]{
new KeyValuePair<string, string>("Arg", "АБ")
}))
{
query = content.ReadAsStringAsync().Result;
}

Console.WriteLine(query);

您也可以用谷歌搜索“querystring builder c#”来查看其他人提出的解决方案。

关于c# - 更改 HttpValueCollection 对参数进行编码的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49519794/

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