Search code examples
c#asp.netrestlong-polling

GET request doesn't work when returned List<> contains items


I'm running into a strange problem while working on a .NET REST application. I can make all sorts of requests just fine, but this one long-polling-GET-interruption request only succeeds if the returned List is empty. To illustrate:

public async Task<List<Person>> UpdateRequest()
{
    try
    {
        await LongPolling(10000);
    }
    catch (TaskCanceledException)
    {
        Console.WriteLine("Long polling GET was cancelled.");
        var fooList = new List<Person>();
        fooList.Add(new Person("tim", "bar")); // <- adding this line breaks the request

        return fooList;
    }

    return null; //Timeout, aka nothing happened
}

When the .Add() line is not there, calling mysite.com/update (and subsequent interrupting of the long GET) returns

<ArrayOfPerson xmlns="http://schemas.datacontract.org/stuff" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>

which is expected, but when the List contains items, I get an instant "Could not get a response". The Console.Writeline is printed. Am I misunderstanding the way List works in C#? Or maybe I'm going wrong with the return type Task<List<Person>>?

Edit: tried it with a normal array: Person[0] is the only thing that works, bigger arrays "Could not get a response" regardless if there's items in them.


Solution

  • Apparently the culprit was not Task<>. Non-async methods (with List<Person> as return type) had the same problem. The client simply does not know how to map a non-empty list of custom objects to a response, which is understandable in hindsight.

    I ended up explicitly mapping the List to XML inside the UpdateRequest() method, resulting in Task<XElement> being the new return type.