0

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?

Community
  • 1
  • 1
Coastpear
  • 374
  • 2
  • 15

3 Answers3

1

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;
}
BMac
  • 2,183
  • 3
  • 22
  • 30
  • It didn't resolve my problem but lead me to a possible resolution, using StringContent instead I can flush the content to the browser the only problem is that it not comes with the content type "applicataion/json" but with "text/plaintext" – Coastpear Nov 10 '15 at 14:05
0

Have you tried setting the MaxJsonDeserializerMembers in web.config?

<appSettings>
      <add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
    </appSettings>
sjokkogutten
  • 2,005
  • 2
  • 21
  • 24
  • Yes, it didn't work because that config it's for asp.net runtime and not for internal javascriptSerializer usage. This "internal javascriptSerializer" doesn't look for any config in the web.config. But thanks anyway. :) – Coastpear Nov 10 '15 at 12:30
0

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;
}
Coastpear
  • 374
  • 2
  • 15