Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Web API returns multiple types

Tags:

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?

like image 301
Matt Avatar asked Jul 31 '12 04:07

Matt


People also ask

How do I return multiple values in API?

try with return Ok(new { firstList = firstList, secondList = secondList }); which will return a new object with two properties named firstList and secondList .

How can you pass multiple complex types in Web API?

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.

Can we have multiple get methods in Web API?

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.


1 Answers

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

like image 167
cuongle Avatar answered Sep 19 '22 10:09

cuongle