简体   繁体   English

UrlEncode通过控制台应用程序?

[英]UrlEncode through a console application?

Normally I would just use: 通常我会使用:

HttpContext.Current.Server.UrlEncode("url");

But since this is a console application, HttpContext.Current is always going to be null . 但由于这是一个控制台应用程序,因此HttpContext.Current始终为null

Is there another method that does the same thing that I could use? 还有另一种方法可以使用我可以使用的相同方法吗?

Try this! 试试这个!

Uri.EscapeUriString(url);

Or 要么

Uri.EscapeDataString(data)

No need to reference System.Web. 无需参考System.Web。

Edit: Please see another SO answer for more... 编辑:请参阅另一个 SO答案了解更多......

I'm not a .NET guy, but, can't you use: 我不是.NET的人,但是,你不能使用:

HttpUtility.UrlEncode Method (String)

Which is described here: 这里描述的是:

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

The code from Ian Hopkins does the trick for me without having to add a reference to System.Web. Ian Hopkins的代码为我提供了诀窍,无需添加对System.Web的引用。 Here is a port to C# for those who are not using VB.NET: 对于那些不使用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));
    }
}

You'll want to use 你会想要使用

System.Web.HttpUtility.urlencode("url")

Make sure you have system.web as one of the references in your project. 确保将system.web作为项目中的引用之一。 I don't think it's included as a reference by default in console applications. 我不认为它在控制台应用程序中默认包含为参考。

Try using the UrlEncode method in the HttpUtility class. 尝试在HttpUtility类中使用UrlEncode方法。

  1. http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx

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

I ran into this problem myself, and rather than add the System.Web assembly to my project, I wrote a class for encoding/decoding URLs (its pretty simple, and I've done some testing, but not a lot). 我自己遇到了这个问题,而不是将System.Web程序集添加到我的项目中,我编写了一个用于编码/解码URL的类(它很简单,我做了一些测试,但不是很多)。 I've included the source code below. 我在下面列出了源代码。 Please: leave the comment at the top if you reuse this, don't blame me if it breaks, learn from the code. 请:如果您重复使用,请将评论保留在顶部,如果它中断,请不要责怪我,请从代码中学习。

''' <summary>
''' URL encoding class.  Note: use at your own risk.
''' Written by: Ian Hopkins (http://www.lucidhelix.com)
''' Date: 2008-Dec-23
''' </summary>
Public Class UrlHelper
    Public Shared Function Encode(ByVal str As String) As String
        Dim charClass = String.Format("0-9a-zA-Z{0}", Regex.Escape("-_.!~*'()"))
        Dim pattern = String.Format("[^{0}]", charClass)
        Dim evaluator As New MatchEvaluator(AddressOf EncodeEvaluator)

        ' replace the encoded characters
        Return Regex.Replace(str, pattern, evaluator)
    End Function

    Private Shared Function EncodeEvaluator(ByVal match As Match) As String
    ' Replace the " "s with "+"s
        If (match.Value = " ") Then
            Return "+"
        End If
        Return String.Format("%{0:X2}", Convert.ToInt32(match.Value.Chars(0)))
    End Function

    Public Shared Function Decode(ByVal str As String) As String
        Dim evaluator As New MatchEvaluator(AddressOf DecodeEvaluator)

        ' Replace the "+"s with " "s
        str = str.Replace("+"c, " "c)

        ' Replace the encoded characters
        Return Regex.Replace(str, "%[0-9a-zA-Z][0-9a-zA-Z]", evaluator)
    End Function

    Private Shared Function DecodeEvaluator(ByVal match As Match) As String
        Return "" + Convert.ToChar(Integer.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber))
    End Function
End Class

Kibbee offers the real answer. Kibbee提供了真正的答案。 Yes, HttpUtility.UrlEncode is the right method to use, but it will not be available by default for a console application. 是的,HttpUtility.UrlEncode是正确的使用方法,但默认情况下它不适用于控制台应用程序。 You must add a reference to System.Web. 必须添加对System.Web的引用。 To do that, 要做到这一点,

  1. In your solution explorer, right click on references 在解决方案资源管理器中,右键单击引用
  2. Choose "add reference" 选择“添加参考”
  3. In the "Add Reference" dialog box, use the .NET tab 在“添加引用”对话框中,使用.NET选项卡
  4. Scroll down to System.Web, select that, and hit ok 向下滚动到System.Web,选择它,然后点击确定

NOW you can use the UrlEncode method. 现在您可以使用UrlEncode方法。 You'll still want to add, 你仍然想要添加,

using System.Web 使用System.Web

at the top of your console app or use the full namespace when calling the method, 在控制台应用程序的顶部或在调用方法时使用完整的命名空间,

System.Web.HttpUtility.UrlEncode(someString) System.Web.HttpUtility.UrlEncode(someString)

System.Web中的HttpUtility.UrlEncode(“url”)。

使用静态HttpUtility.UrlEncode方法。

Best thing is to Add Reference to System.web..dll 最好的方法是添加对System.web..dll的引用

and use var EncodedUrl=System.Web.HttpUtility.UrlEncode("URL_TEXT"); 并使用var EncodedUrl = System.Web.HttpUtility.UrlEncode(“URL_TEXT”);

You can find the File at System.web.dll 您可以在System.web.dll找到文件

Uri.EscapeUriString should not be used for escaping a string to be passed in a URL as it does not encode all characters as you might expect. Uri.EscapeUriString不应该用于转义要在URL中传递的字符串,因为它不会像您期望的那样对所有字符进行编码。 The '+' is a good example which is not escaped. '+'是一个很好的例子,没有被转义。 This then gets converted to a space in the URL since this is what it means in a simple URI. 然后将其转换为URL中的空格,因为这是在简单URI中的含义。 Obviously that causes massive issues the minute you try and pass something like a base 64 encoded string in the URL and spaces appear all over your string at the receiving end. 显然,只要您尝试在URL中传递类似base 64编码的字符串,并且在接收端的字符串中出现空格,就会导致大量问题。

You can use HttpUtility.UrlEncode and add the required references to your project (and if you're communicating with a web application then I see no reason why you shouldn't do this). 您可以使用HttpUtility.UrlEncode并将所需的引用添加到您的项目中(如果您正在与Web应用程序通信,那么我认为没有理由不这样做)。

Alternatively use Uri.EscapeDataString over Uri.EscapeUriString as explained very well here: https://stackoverflow.com/a/34189188/7391 或者在Uri.EscapeUriString上使用Uri.EscapeDataString,如下所述: https ://stackoverflow.com/a/34189188/7391

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过Windows Forms应用程序启用控制台应用程序 - Enabling a console application through a Windows Forms application 通过窗口服务调用控制台应用程序 - Calling a Console application through a Window Service 通过控制台应用程序使用Microsoft Web Deploy - Using Microsoft Web Deploy through Console Application 通过HttpClient的HTTP Post的UrlEncode非字符串属性 - UrlEncode non-string properties for HTTP Post through HttpClient 如何通过C#控制台应用程序读取邮件内容 - How to read mail content through c# console application 如何使用 c# 中的按键来浏览控制台应用程序? - How to use keys in c# to navigate through a console application? 通过新的C#交互式控制台交互/操纵应用程序的值 - Interact/manipulate Values of Application through the new C# Interactive Console SSIS包错误-通过C#控制台应用程序执行 - SSIS Package Error - Executing through C# Console Application 如何通过C#控制台应用程序更新MySql表行? - How to update MySql table row through C# console application? 在 .NET Core 控制台应用程序中通过依赖注入访问配置 - Access configuration through dependency injection in .NET Core console application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM