DavidSpot Blog

Developer, super curious, a dog lover, sports fan and techie guy


Bypassing Web API JSON Property Length Limit

Did you haver encouter a weird bug while working with Web API like this: 

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property

If you did, probably your next action was googling for a solution and very likely you stop in StackoverFlow with a lot's of answers. 

The most usual response to this issue it's to do one of three things

  • Go to Web.Config and change the proporty jsonSerialization maxJsonLength to the max value, witch is int.MaxValue like this
<configuration> 
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>

 

  • Add a special web.config key to appSettings:
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>

 

  • Or if you are using .NET MVC in a override de Json method in a controller
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}

 

The problem with all this solutions is none of them addresses the problem for a Web API. After a few time doing some tests I came up with a simple, yet hackie solution that looks like this:

[HttpGet]
//ResponseType it's for ApiDescription successfully generates the helper page with the right type since i'm returning a plain/text content
[ResponseType(typeof(YourType))]
public async Task<HttpResponseMessage> GetLargeJsonDataWithWebAPI()
{
    String url = "someUrl";
    String jsonData = EnvironmentUrlHelper.GetJsonResourseAsync<YourType>(url);


    var response = Request.CreateResponse();
    response.Content = new StringContent(JsonConvert.SerializeObject(rsp));

    return response;
}

What I'm doing is telling the Http that I'm not returning an application/Json result but instead a plain text (text/plain) witch is myobject serialized in JSON. By doing this we bypass the limit validation and can return large JSON data, though this is not recomended to do it's a nice way to play around with the framework.

In case you're asking what the hell his the attribute ResponseType, because I'm using the HelpPage nuget package, this enables the ApiDescription to resolve witch type the method returns.

Since I'm returning a HttpResponseMessage to do this bypass, if didn't use this attribute the HelpPage would use the for the return type the Type HttpResponseMessage instead of "YourType".