ASP.NET的JavaScriptSerializer需要的Htt presponse? [英] ASP.NET JavaScriptSerializer requires HttpResponse?

查看:133
本文介绍了ASP.NET的JavaScriptSerializer需要的Htt presponse?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来,System.Web.Script.Serialization.JavascriptSerializer类尝试获取当前请求,presumably采取适当的字符编码​​型Htt presponse。

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.

然而,这意味着,当你与范围没有HttpContext的使用类,它与下面的异常+堆栈跟踪打击了:

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

我不能返工code以这样一种方式,以保证有效的HttpContext的存在。如何避免这种情况的任何想法?可能字符串类型的定制JavascriptConverter是一个强大的解决方案?

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?

感谢

帕斯卡尔

推荐答案

据我所知<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\">JavaScriptSerializer不需要任何的HttpContext并在控制台应用程序工作完全正常:

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);
    }
}

您也可以尝试 Json.NET

这篇关于ASP.NET的JavaScriptSerializer需要的Htt presponse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆