I have Web API developed in .Net core. I want to return different data model from the same Action method for different clients.
.Net Core Web API to return different data models to different clients
4.4k Views Asked by Rabia Basri At
3
There are 3 best solutions below
2

If you are not developing microservices, usually it is not good idea having multiple result set in one endpoint. But if you need you can use IActionResult Type . With this type you don't have to declare a fixed return type. You can use like this.
[HttpGet("list/{clientType}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult ReturnSomeList(int clientType)
{
var firstList = new List<string>();
for (int i = 0; i < 3; i++)
{
firstList.Add($"str {i}");
}
var secondList = new List<int>();
for (int i = 0; i < 5; i++)
{
secondList.Add(i);
}
if (clientType == 0)
{
return Ok(firstList);
}
if (clientType == 1)
{
return Ok(secondList);
}
return NotFound("Can not find something");
}
0

You can return any model you want from one endpoint by declaring return type as Task<IActionResult>
.
Suppose you have a CustomersController
, so GET
endpoint will be api/customers?clientType=client1
. Now you want customer's different information for a different based on clientType
parameter.
namespace walletapi.Controllers
{
[ApiController]
[Authorize]
public class CustomersController : ControllerBase
{
public async Task<IActionResult> Get(string clientType)
{
if(clientType=="type1"){
var type1Response = new CustomerInfoForClient1() {Property1="value1"};
return Ok(type1Response );
}
if(clientType=="type2"){
var type2Response = new CustomerInfoForClient2() {Property1="value2"};
return Ok(type2Response);
}
return NotFound("client type is not found");
}
}
public class CustomerInfoForClient1
{
public string Property1{get;set;}
}
public class CustomerInfoForClient2
{
public string Property3{get;set;}
}
}
You can change the result of actions based on different options, but clients would be weird and I never see someone or a project that would do this, it will make the debug harder. When a service works, it always should expose expected behavior, we should know when it's successful it give us a person object, when it fails, it return a failure message, changing the frame for clients is the worst scenario. A better way to meet this requirement would be different API, when clients need different result, we must expose different API and these separate APIs should respect to the above rule.