【问题标题】:Unable to encode Url properly using HttpUtility.UrlEncode() method无法使用 HttpUtility.UrlEncode() 方法正确编码 Url
【发布时间】:2014-06-25 17:53:46
【问题描述】:

我创建了一个应用程序,我需要在其中对用户输入的 url 中的特殊字符进行编码/解码。

例如:如果用户输入http://en.wikipedia.org/wiki/Å,那么相应的Url应该是http://en.wikipedia.org/wiki/%C3%85

我用以下代码制作了控制台应用程序。

string value = "http://en.wikipedia.org/wiki/Å";
Console.WriteLine(System.Web.HttpUtility.UrlEncode(value));

它成功地解码了字符Å,并且还编码了://字符。运行代码后,我得到如下输出:http%3a%2f%2fen.wikipedia.org%2fwiki%2f%c3%85 但我想要http://en.wikipedia.org/wiki/%C3%85

我该怎么办?

【问题讨论】:

    标签: c# url encoding


    【解决方案1】:

    Uri.EscapeUriString(value) 返回您期望的值。但它可能还有其他问题。

    .NET Framework 中有一些 URL 编码函数,它们的行为各不相同,在不同的情况下很有用:

    1. Uri.EscapeUriString
    2. Uri.EscapeDataString
    3. WebUtility.UrlEncode(仅在 .NET 4.5 中)
    4. HttpUtility.UrlEncode(在 System.Web.dll 中,用于 Web 应用程序,而不是桌面)

    【讨论】:

      【解决方案2】:

      您可以使用正则表达式选择主机名,然后仅对字符串的其他部分进行 urlencode:

      var inputString = "http://en.wikipedia.org/wiki/Å";
      var encodedString;
      var regex = new Regex("^(?<host>https?://.+?/)(?<path>.*)$");
      
      var match = regex.Match(inputString);
      if (match.Success)
          encodedString = match.Groups["host"] + System.Web.HttpUtility.UrlEncode(match.Groups["path"].ToString());
      
      Console.WriteLine(encodedString);
      

      【讨论】:

        猜你喜欢
        • 2020-11-26
        • 2011-09-08
        • 2016-07-18
        • 1970-01-01
        • 2012-08-30
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多