0
votes

I'm trying to return a large set o json (about 2MB) but the web api returns the error:

"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property". I've tried configure the maxJsonLength property in the web.config but without success.

I've seen another answers in the stackoverflow but all related to a regular .NET MVC Controller and not an ApiController.

It's possible to bypass the internal JavaScriptSerializer maxJsonLenght or by doing some custom JsonSerializerType format?

3
Hi @Coastpear what version of webapi are you using? depending on which version you are using the override will change a little. - BMac
I'm using version 5.1.0.0 - Coastpear

3 Answers

1
votes

Depending on just how large the JSON payload becomes, you may have to stream the response. See this blog post. In short that blog post can be summarised by the below code:

[HttpGet]
public HttpResponseMessage PushStreamContent()
{
    var response = Request.CreateResponse();

    response.Content = 
    new PushStreamContent((stream, content, context) =>
    {
        foreach (var staffMember in _staffMembers)
        {
            var serializer = new JsonSerializer();
            using (var writer = new StreamWriter(stream))
            {
                serializer.Serialize(writer, staffMember);
                stream.Flush();
            }
        }
    });

    return response;
}
0
votes

Have you tried setting the MaxJsonDeserializerMembers in web.config?

<appSettings>
      <add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
    </appSettings>
0
votes

Thanks @BMac for your help, you lead me to a solution that works.

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