user3953989 user3953989 - 1 month ago 11
C# Question

Web Api 2 OkResult not passing generic lists

Using Fiddler to test, the following web api 2 method will return the object with the Success property filled out correctly but the Results property is always empty. Stepping through the debugger there is data in the list but not sent as part of the response.

The objects I'm returning are proxy objects generated by EF which might have something to do with it as well.

public class ApiResult<T>
{
public ApiResult()
{
Results = new List<T>();
}

public bool Success { get; set; }
public List<T> Results { get; set; }
}


[HttpGet]
[Route("test")]
public IHttpActionResult test()
{
ApiResult<User> rv = new ApiResult<User>();
rv.Success = true;
rv.Results.Add(new User { name = "Steve" })
rv.Results.Add(new User { name = "Dave" })

return Ok(rv);
}


JSON Result

{"Success":true,"Results":[{},{}]}


WebApiConfig.cs

config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Answer

You are defining the property Results as a list of object. Since the type object doesn't have any property the serializer return an empty object. Try defining Results as a list of User like this:

public class ApiResult
{
    public ApiResult()
    {
        Results = new List<User>();
    }

    public bool Success { get; set; }
    public List<User> Results { get; set; }
}
Comments