views:

33

answers:

1

Hi

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

A: 

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.

Darin Dimitrov
Interesting. Perhaps it tries to determine if a HttpContext is available, and if it is, it also assumes availability of HttpResponse? I can move this to a place where both HttpContext and HttpResponse are available if it will work when there is no HttpContext whatsoever. I'll try that.
Pascal
Exactly. That's it. If HttpContext.Current is not null it assumes HttpContext.Current.Response is not null.
Darin Dimitrov
VinayC