根据http://ayende.com/blog/4599/hunt-the-bug,我遇到了其中一种情况,即“在这种情况下无法提供响应”。
非常简化,以下内容在Windows Server 2008 / IIS7 / ASP.NET 4.0的某些情况下引发异常
public class Global : HttpApplication
{
public void Application_Start(object sender, EventArgs e)
{
HttpUtility.UrlEncode("Error inside!");
}
}
我见过的解决方案涉及以下其中一项:
也许这不是我最好的谷歌搜索日,但如何实现HttpEncoder.Default?
建议?
答案 0 :(得分:3)
您可以尝试使用此功能进行编码
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,最好的方法是什么!..
答案 1 :(得分: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;
}
}
}