UrlEncode通过控制台应用程序?

Kev*_*nUK 61 .net c# console

通常我会使用:

HttpContext.Current.Server.UrlEncode("url");
Run Code Online (Sandbox Code Playgroud)

但由于这是一个控制台应用程序,HttpContext.Current所以总会如此null.

还有另一种方法可以使用我可以使用的相同方法吗?

Ost*_*ati 78

试试这个!

Uri.EscapeUriString(url);
Run Code Online (Sandbox Code Playgroud)

要么

Uri.EscapeDataString(data)
Run Code Online (Sandbox Code Playgroud)

无需参考System.Web.

编辑:请参阅另一个 SO答案了解更多......

  • 谢谢你提供答案,而非答案. (3认同)
  • 当@KevinUK要求编码时,这与```HttpUtility.UrlEncode```不同. (3认同)
  • 这是一个更好的答案,因为您不必导入对控制台应用程序的新引用,因为`Uri`类在`System`中. (2认同)

And*_*lor 72

我不是.NET的人,但是,你不能使用:

HttpUtility.UrlEncode Method (String)
Run Code Online (Sandbox Code Playgroud)

这里描述的是:

MSDN上的HttpUtility.UrlEncode方法(字符串)

  • 您需要(必须)添加System.Web作为参考.简单地使用System.Web是不够的 (26认同)
  • 我不想在每个人的游行中下雨,但是即使我使用"使用System.Web",提到的HttpUtility.UrlEncode似乎也不可见.这实际上适用于某人,如果可以,您可以包含实际代码吗? (3认同)

t3r*_*rse 13

Ian Hopkins的代码为我提供了诀窍,无需添加对System.Web的引用.对于那些不使用VB.NET的人来说,这是一个C#的端口:

/// <summary>
/// URL encoding class.  Note: use at your own risk.
/// Written by: Ian Hopkins (http://www.lucidhelix.com)
/// Date: 2008-Dec-23
/// (Ported to C# by t3rse (http://www.t3rse.com))
/// </summary>
public class UrlHelper
{
    public static string Encode(string str) {
        var charClass = String.Format("0-9a-zA-Z{0}", Regex.Escape("-_.!~*'()"));
        return Regex.Replace(str, 
            String.Format("[^{0}]", charClass),
            new MatchEvaluator(EncodeEvaluator));
    }

    public static string EncodeEvaluator(Match match)
    {
        return (match.Value == " ")?"+" : String.Format("%{0:X2}", Convert.ToInt32(match.Value[0]));
    }

    public static string DecodeEvaluator(Match match) {
        return Convert.ToChar(int.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber)).ToString();
    }

    public static string Decode(string str) 
    {
        return Regex.Replace(str.Replace('+', ' '), "%[0-9a-zA-Z][0-9a-zA-Z]", new MatchEvaluator(DecodeEvaluator));
    }
}
Run Code Online (Sandbox Code Playgroud)


Kib*_*bee 6

你会想要使用

System.Web.HttpUtility.urlencode("url")
Run Code Online (Sandbox Code Playgroud)

确保将system.web作为项目中的引用之一.我不认为它在控制台应用程序中默认包含在参考中.


Dev*_*ies 6

WebUtility.UrlEncode(string)System.Net命名空间使用

  • 值得一提的是,此方法从 .NET 4.0 开始可用。 (2认同)