As per http://ayende.com/blog/4599/hunt-the-bug, I've run into one of those scenarios whereby "Response is not available in this context".
Greatly simplified, the following throws an exception in certain scenarios on 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 that I've seen involve one of the following:
Maybe it's not my best googling day, but how to implement HttpEncoder.Default?
Recommendations?
The UrlEncode method can be used to encode the entire URL, including query-string values. If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the receiving end.
HtmlEncode Method (System. Web) Converts a string into an HTML-encoded string. To encode or decode values outside of a web application, use the WebUtility class.
UrlEncode is a convenient way to access the HttpUtility. UrlEncode method at run time from an ASP.NET application. Internally, UrlEncode uses HttpUtility. UrlEncode to encode strings. To encode or decode values outside of a web application, use the WebUtility class.
You can try this for encoding
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;
}
And if you don't feel comfortable with or your application is not running in FULL trust level, try this
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);
}
}
I Know it is not still the best way but what could the best way be if we don't use HttpUtility.UrlEncode!..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With