哪些 c# 桌面应用编码方法编码以匹配此编码



我正在尝试对以下字符串进行编码以构建URL

字符串: Radio Signal Gabriel Moraes,fernando De Sá

在此网站上对该字符串进行编码 https://www.urlencoder.org/得到: Radio%20Signal%20Gabriel%20Moraes%2Cfernando%20De%20S%C3%A1

当我尝试在 C# 中模拟该编码时,我似乎找不到一种方法来做到这一点。

HttpUtility.UrlPathEncode(str);给出: Radio+Signal+Gabriel+Moraes%2CFernando+de+S%E1

Uri.EscapeDataString(str);给出: Radio+Signal+Gabriel+Moraes%2CFernando+de+S%E1

Uri.EscapeUriString(str);给出: Radio+Signal+Gabriel+Moraes%2CFernando+de+S%E1

HttpUtility.UrlEncode(str);给出: Radio+Signal+Gabriel+Moraes%2CFernando+de+S%E1

HttpUtility.UrlEncode(str, Encoding.UTF8); Radio+Signal+Gabriel+Moraes%2CFernando+de+S%E1

urlencoder 网站上返回的编码结果适用于我尝试使用它的网站,而其他网站则不然。

.NET 4.5 桌面框架中是否有可用的 C# 方法,该方法将执行与 urlencoder 网站相同的编码?

我不确定你是如何得到你所做的结果的,但一个简单的测试表明,你计算出的选项之一完全符合你想要的。

我设置的简单测试:

const string expected = "Radio%20Signal%20Gabriel%20Moraes%2Cfernando%20De%20S%C3%A1";
string input = "Radio Signal Gabriel Moraes,fernando De Sá";
    
var functionDict = new Dictionary<string, Func<string, string>>()
{
    { "HttpUtility.UrlPathEncode", x => HttpUtility.UrlPathEncode(x) },
    { "Uri.EscapeDataString", x => Uri.EscapeDataString(x) },
    { "Uri.EscapeUriString", x => Uri.EscapeUriString(x) },
    { "HttpUtility.UrlEncode", x => HttpUtility.UrlEncode(x) }
};
Console.WriteLine("Functions that match expected output:");
foreach(var f in functionDict)
{
    string result = f.Value(input);
    
    if(string.Compare(result, expected) == 0)
    {
        Console.WriteLine(f.Key);
    }
}

这将给出以下输出:

与预期输出匹配的函数:

Uri.EscapeDataString

所以我想也许你应该再看看Uri.EscapeDataString()

在这里摆弄

最新更新