UrlEncode a través de una aplicación de consola?


Normalmente solo usaría:

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

Pero como esta es una aplicación de consola, HttpContext.Current siempre será null.

¿Hay otro método que haga lo mismo que yo podría usar?

Author: Michał Powaga, 2008-08-18

12 answers

Prueba esto!

Uri.EscapeUriString(url);

O

Uri.EscapeDataString(data)

No hay necesidad de sistema de referencia.Web.

Editar: Por favor vea otro Así que responda para más...

 70
Author: ostati,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-20 22:04:25

No soy un chico. NET, pero, no se puede utilizar:

HttpUtility.UrlEncode Method (String)

Que se describe aquí:

HttpUtility.Método UrlEncode (Cadena) en MSDN

 72
Author: Andrew Taylor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-12 09:58:30

El código de Ian Hopkins hace el truco para mí sin tener que agregar una referencia al Sistema.Web. Aquí hay un puerto a C# para aquellos que no están usando VB.NET:

/// <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));
    }
}
 13
Author: t3rse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-16 21:36:20

Usted querrá usar

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

Asegúrese de que tiene sistema.web como una de las referencias en tu proyecto. No creo que esté incluido como referencia por defecto en las aplicaciones de consola.

 7
Author: Kibbee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-29 19:39:06

Intente usar el método UrlEncode en la clase HttpUtility.

  1. http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx
 4
Author: Patrik Svensson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-18 14:50:38

Me encontré con este problema yo mismo, y en lugar de agregar el Sistema.Web assembly para mi proyecto, escribí una clase para codificar / decodificar URLs (es bastante simple, y he hecho algunas pruebas, pero no muchas). He incluido el código fuente a continuación. Por favor: deja el comentario en la parte superior si reutilizas esto, no me culpes si se rompe, aprende del código.

''' <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
 3
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-24 02:43:34

Use WebUtility.UrlEncode(string) desde System.Net espacio de nombres

 3
Author: Devson Technologies,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-30 00:12:31

Kibbee ofrece la verdadera respuesta. Sí, HttpUtility.UrlEncode es el método correcto para usar, pero no estará disponible de forma predeterminada para una aplicación de consola. debe agregar una referencia al Sistema.Web. Para hacer eso,

  1. En su explorador de soluciones, haga clic derecho en referencias
  2. Elija "añadir referencia"
  3. En el cuadro de diálogo" Agregar referencia", use la pestaña. NET
  4. Desplácese hacia abajo hasta Sistema.Web, seleccione eso y pulse ok

AHORA puedes usar el UrlEncode método. Usted todavía querrá agregar,

Usando el Sistema.Web

En la parte superior de la aplicación de consola o use el espacio de nombres completo al llamar al método,

Sistema.Web.HttpUtility.UrlEncode (someString)

 2
Author: Anjisan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-16 15:08:21

HttpUtility.UrlEncode ("url") en el sistema.Web.

 1
Author: Vaibhav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-18 14:51:37

Utilice el HttpUtility estático.Método UrlEncode.

 1
Author: TheSmurf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-18 14:52:08

Lo mejor es agregar Referencia al Sistema.web..dll

Y uso var EncodedUrl=Sistema.Web.HttpUtility.UrlEncode ("URL_TEXT");

Puede encontrar el archivo en System.web.dll

 0
Author: Girjesh Kumar Vishwakarma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-23 12:14:42

Uri.EscapeUriString no debe usarse para escapar una cadena que se pase en una URL, ya que no codifica todos los caracteres como cabría esperar. El ' + ' es un buen ejemplo que no se escapa. Esto luego se convierte en un espacio en la URL, ya que esto es lo que significa en un URI simple. Obviamente, eso causa problemas masivos en el momento en que intenta pasar algo como una cadena codificada en base 64 en la URL y los espacios aparecen en toda la cadena en el extremo receptor.

Puede utilizar HttpUtility.UrlEncode y agrega las referencias requeridas a tu proyecto (y si te estás comunicando con una aplicación web, entonces no veo ninguna razón por la que no deberías hacer esto).

Alternativamente use Uri.Escapé de una cacería sobre Uri.EscapeUriString como se explica muy bien aquí: https://stackoverflow.com/a/34189188/7391

 0
Author: Jason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-15 11:09:39