ASP.NET JavaScriptSerializer requires HttpResponse?

别等时光非礼了梦想. 提交于 2019-12-10 18:45:31

问题


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.



来源:https://stackoverflow.com/questions/3881289/asp-net-javascriptserializer-requires-httpresponse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!