6

My application is an ASP.NET Core 1.0 Web API.

If my Controller Returns a small JSON, everything works fine. However, if the JSON gets bigger, I am getting this error

Visual Studio is giving me this error

This is the Controller and the Method that creates the Data (shortened)

  [HttpGet]
  public async Task<IActionResult> GetUserData()
  {        
        return this.Ok(GetSomeData());
  }

   private List<MyUser> GetSomeData()
   {
       var userList = new List<MyUser>();
       for (int i = 0; i < 2500; i++)
       {
            userList.Add(new MyUser{
                Name = "Data",
                Age = i,
                Phone = "000",
            });
       }
       return userList;
   }

If the loop is getting to big, Iam getting the errors listed above.

Keep in mind that the code is extremely simplified. But everything works fine, until to much data is returned.

I have tried to change the maxJsonLength in the web.config as it's described here.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Moritz Schmidt
  • 2,635
  • 3
  • 27
  • 51
  • For whoever is interested, my question got answered in [this](http://stackoverflow.com/questions/42924571/microsoft-windowsazure-storage-storageexception-badrequest-strings-32768-azur) post. – Moritz Schmidt Mar 23 '17 at 08:19

2 Answers2

0

See, with web api and json there is a limit to the amount of data you can transfer. But a quirky way could be to return a text/plain data serialized as json.

So if you changed your GetUserData() action as such:

[HttpGet]
public async Task<HttpResponseMessage> GetUserData()
{     
   var result = GetSomeData();
   var response = Request.CreateResponse();
   response.Content = new StringContent(JsonConvert.SerializeObject(result));
   return response;
}

And then in your client, you can construct your object back by using JsonConvert.DeserializeObject method.

Jinish
  • 1,983
  • 1
  • 17
  • 22
  • Thanks for your answer. This doesnt work for me.. When i try to get the package "Microsoft.AspNet.WebApi.Core", Iam getting the error message that it's not compatble with "netcoreapp1.0". Therefore I dont have the Method CreateResponse(); Do you have any other advices? – Moritz Schmidt Mar 17 '17 at 08:21
  • I found a workaround to get the Response object here [link](http://stackoverflow.com/questions/15816049/web-api-request-createresponse-httpresponsemessage-no-intellisense-vs2012) I shall use HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.Gone) instead of Request.CreateResponse() But this doesnt work for me.. – Moritz Schmidt Mar 17 '17 at 09:07
0

My problem was that I had a middleware that throw exception and closed response too soon

Dživo Jelić
  • 1,723
  • 3
  • 25
  • 47