Search code examples
c#asp.netjsonashx

Proper way to use Context.Response.Write() on a very long Json string


I am using iis and asp.net with c#.

I have a JSON string which I build using JavaScriptSerializer, with MaxJsonLength set as Int32.MaxValue, now I want to return this using response.write, like this Response.Write(myJsonString), but I am wondering is this the proper way to return it? Are there any problems if the string is very long (may contain huge base 64 encoded bytes too) if it still falls within the int32.maxvalue length, is there any limitation from IIS itself (as in the maximum length I can return)? Or should I write a loop to send the string character by character and flush the response every x number of characters?

As an aside, should I add a UTF8 BOM to the front of the response.write to ensure that I can consume the JSON string properly on the receiver's end? Are there any implications if the JSON string contains base64 encoded bytes?


Solution

  • now i want to return this using response.write, like this Response.Write(myJsonString), but i am wondering is this the proper way to return it?

    Instead of using the JavaScriptSerializer class you might consider using JSON.NET or the built-in DataContractJsonSerializer which both allow you to serialize directly to the output stream:

    var serializer = new JsonSerializer();
    serializer.Serialize(context.Response.Output, objectToSerialize);
    

    This way you don't need to be loading the entire JSON string in memory.

    are there any problems if the string is very long (may contain huge base 64 encoded bytes too) if it still falls within the int32.maxvalue length, is there any limitation from iis itself (as in the maximum length i can return)

    As far as IIS is concerned, I don't think there would be problems. But as I mentioned earlier you would be consuming lots of memory on your server if you perform the serialization into a string instead of directly streaming it to the client.

    or should i write a loop to send the string character by character and flush the reponse every x number of characters?

    This wouldn't help much as you still have the entire JSON string in memory.

    as an aside i wanna ask too, should i add a ut8 bom to the front of the response.write to ensure that i can consume the json string properly on the receiver's end?

    If you use one of the 2 JSON serializers I mentioned previously and write the resulting JSON directly to the response stream they will take care of adding this character.