.Net Core Web API将不同的数据模型返回到不同的客户端



我有在.Net核心中开发的Web API。我想为不同的客户端从相同的Action方法返回不同的数据模型。

您可以根据不同的选项更改操作的结果,但客户端会很奇怪,我从来没有见过有人或项目会这样做,这会使调试更加困难。当服务工作时,它总是应该公开预期的行为,我们应该知道,当它成功时,它会给我们一个人对象,当它失败时,它返回一条失败消息,改变客户端的框架是最糟糕的情况。满足这一要求的更好方法是使用不同的API,当客户端需要不同的结果时,我们必须公开不同的API,并且这些单独的API应遵守上述规则。

通过将返回类型声明为Task<IActionResult>,可以从一个端点返回任何所需的模型。

假设您有一个CustomersController,那么GET端点将是api/customers?clientType=client1。现在,您需要基于clientType参数的不同客户的不同信息。

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;}
}
}

如果您不是在开发微服务,通常在一个端点中设置多个结果集是不好的。但如果需要,可以使用IActionResult类型。使用此类型,您不必声明固定的返回类型。你可以这样使用。

[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");
}

最新更新