HttpUtility.UrlEncode and Application_Start

According to http://ayende.com/blog/4599/hunt-the-bug , I came across one of those scenarios in which "The answer is not available in this context."

Significantly simplified, the following throws an exception in some scenarios of Windows Server 2008 / IIS7 / ASP.NET 4.0

public class Global : HttpApplication
{
       public void Application_Start(object sender, EventArgs e)
       {
            HttpUtility.UrlEncode("Error inside!");
       }
}    

The solutions I've seen include one of the following:

  • Do as Iyend did, and "write my own HttpUtility (well, take it from Mono and change it) to avoid this error.
  • or determine if this method uses HttpEncoder.Default. I am trying to track how best to do this.
  • or use Uri.EscapeDataString by Server.UrlEncode vs HttpUtility.UrlEncode

, Google, HttpEncoder.Default?

+5
2

public static string UrlEncode(string s)
{
    return typeof(System.Net.WebClient).InvokeMember("UrlEncode", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new[] { "[#encoded] <data>" }) as string;
}

// by @DmitryDzygin
public static string UrlDecode(string s)
{
    return typeof(System.Net.WebClient).Assembly.GetType("System.Net.HttpListenerRequest+Helpers").InvokeMember("UrlDecodeStringFromStringInternal", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { s, Encoding.UTF8 }) as string;
}

,

public class HttpUtils : System.Web.Util.HttpEncoder
{
    private static HttpUtils _encoder;
    internal static HttpUtils Encoder
    {
        get { return _encoder ?? (_encoder = new HttpUtils()); }
    }

    internal string InternalUrlEncode(string s)
    {
        var bytes = System.Text.Encoding.UTF8.GetBytes(s);
        var encodedBytes = base.UrlEncode(bytes, 0, bytes.Length);

        return System.Text.Encoding.UTF8.GetString(encodedBytes);
    }

    public static string UrlEncode(string s)
    {
        return Encoder.InternalUrlEncode(s);
    }
}

, , , HttpUtility.UrlEncode!..

+3

public static class DefaultHttpEncoder
{
    public static string UrlEncode(string urlPart)
    {
        using (new NoHttpContext())
        {
            return HttpUtility.UrlEncode(urlPart);
        }
    }

    public static string UrlDecode(string urlPart)
    {
        using (new NoHttpContext())
        {
            return HttpUtility.UrlDecode(urlPart);
        }
    }

    private class NoHttpContext : IDisposable
    {
        private readonly HttpContext _context;

        public NoHttpContext()
        {
            _context = HttpContext.Current;
            HttpContext.Current = null;
        }

        public void Dispose()
        {
            HttpContext.Current = _context;
        }
    }
}
+3

All Articles