问题
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