How Web API returns multiple types

时光毁灭记忆、已成空白 提交于 2021-02-06 09:48:06

问题


I am just wondering whether it is possible to return multiple types in a single Web Api. For example, I want an api to return both lists of customers and orders (these two sets of data may or may not relate to each other?


回答1:


To return multiple types, you can wrap them into anonymous type, there are two possible approaches:

public HttpResponseMessage Get()
{
    var listInt = new List<int>() { 1, 2 };
    var listString = new List<string>() { "a", "b" };

    return ControllerContext.Request
        .CreateResponse(HttpStatusCode.OK, new { listInt, listString });
}

Or:

public object Get()
{
    var listInt = new List<int>() { 1, 2 };
    var listString = new List<string>() { "a", "b" };

    return  new { listInt, listString };
}

Also remember that The XML serializer does not support anonymous types. So, you have to ensure that request should have header:

Accept: application/json

in order to accept json format




回答2:


You have to use JsonNetFormatter serializer, because the default serializer- DataContractJsonSerializer can not serialize anonymous types.

public HttpResponseMessage Get()
{
    List<Customer> cust = GetCustomers();
    List<Products> prod= GetCustomers();
    //create an anonymous type with 2 properties
    var returnObject = new { customers = cust, Products= prod };
    return new HttpResponseMessage<object>(returnObject , new[] { new JsonNetFormatter() });
}

You could get JsonNetFormatter from HERE




回答3:


Instead of this:

return ControllerContext.Request
       .CreateResponse(HttpStatusCode.OK, new { listInt, listString });

use this:

return Ok(new {new List<int>() { 1, 2 }, new List<string>() { "a", "b" }});


来源:https://stackoverflow.com/questions/11733205/how-web-api-returns-multiple-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!