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?
try with return Ok(new { firstList = firstList, secondList = secondList }); which will return a new object with two properties named firstList and secondList .
Best way to pass multiple complex object to webapi services is by using tuple other than dynamic, json string, custom class. No need to serialize and deserialize passing object while using tuple. If you want to send more than seven complex object create internal tuple object for last tuple argument.
As mentioned, Web API controller can include multiple Get methods with different parameters and types. Let's add following action methods in StudentController to demonstrate how Web API handles multiple HTTP GET requests.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With