ASP.NET JavaScriptSerializer requires HttpResponse

2019-07-07 02:25发布

问题:

It appears that the System.Web.Script.Serialization.JavascriptSerializer class tries to obtain the HttpResponse for the current request, presumably to apply appropriate character encoding.

However this means that when you to to use the class with no HttpContext in scope, it blows up with the following exception + stack trace:

[HttpException (0x80004005): Response is not available in this context.]
   System.Web.HttpContext.get_Response() +8753496
   System.Web.Util.HttpEncoder.get_Current() +39
   System.Web.HttpUtility.JavaScriptStringEncode(String value, Boolean addDoubleQuotes) +13
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeString(String input, StringBuilder sb) +31
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +240
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1355
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat) +26
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +74
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj) +6

I cannot rework the code in such a way as to guarantee the existence of a valid HttpContext. Any ideas on how to avoid this? Might a custom JavascriptConverter for the String type be a robust solution?

Thanks

Pascal

回答1:

AFAIK JavaScriptSerializer doesn't require any HttpContext and works perfectly fine in a console application:

class Program
{
    static void Main(string[] args)
    {
        string json = new JavaScriptSerializer().Serialize(new { Bar = "foo" });
        Console.WriteLine(json);
    }
}

You could also try Json.NET.