我有在.Net核心开发的Web API。我想为不同的客户端从相同的Action方法返回不同的数据模型。
发布于 2020-07-14 02:45:20
您可以根据不同的选项更改操作的结果,但客户端会很奇怪,而且我从未见过有人或项目会这样做,这会使调试变得更加困难。当服务工作时,它总是应该公开预期的行为,我们应该知道当它成功时,它会给我们一个person对象,当它失败时,它会返回失败消息,为客户端更改框架是最糟糕的情况。满足这一要求的一个更好的方法是不同的API,当客户端需要不同的结果时,我们必须公开不同的API,这些单独的API应该遵守上面的规则。
发布于 2020-07-14 03:13:44
如果您不是在开发微服务,那么在一个端点中拥有多个结果集通常不是一个好主意。但是如果你需要,你可以使用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");
}
发布于 2020-07-14 14:52:38
通过将返回类型声明为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;}
}
}
https://stackoverflow.com/questions/62881917
复制相似问题