自动生成的c#客户端应该如何处理可以返回不同类型的API调用?
我正在使用具有以下定义的服务:自动生成的c#客户端应该如何处理可以返回不同类型的API调用?,c#,asp.net-core,swagger,autorest,C#,Asp.net Core,Swagger,Autorest,我正在使用具有以下定义的服务: [HttpGet] [SwaggerOperation(nameof(GetAnimal))] [Route("{animalId:long}", Name = nameof(GetAnimal))] [ProducesResponseType(typeof(AnimalModel), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorModel), StatusCodes.Status500I
[HttpGet]
[SwaggerOperation(nameof(GetAnimal))]
[Route("{animalId:long}", Name = nameof(GetAnimal))]
[ProducesResponseType(typeof(AnimalModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ErrorModel), StatusCodes.Status500InternalServerError)]
public Task<IActionResult> GetAnimal(string tenantId, long animalId)
{
try
{
// Find the actual animal.. somewhere.
return Ok(new AnimalModel());
}
catch (Exception exception)
{
return InternalServerError(new ErrorModel());
}
}
问题
处理返回不同对象的API的推荐方法是什么
潜在解决方案
- 我可以修复客户端代码并转换结果以找到正确的类型(不好)李>
- 我可以修改API(如果可能的话),使其只返回一个由
和AnimalModel
组成的对象(可能更好)ErrorModel
ActionResult
返回类型。它使您能够返回从ActionResult
派生的类型或返回特定类型<代码>操作结果比IActionResult
类型提供以下好处:
- 可以排除
属性的[ProducesResponseType]
属性。例如,类型
被简化为[ProducesResponseType(200,Type=typeof(Product))]
。操作的预期返回类型是从[ProducesResponseType(200)]
中的ActionResult
推断出来的T
- 隐式强制转换运算符支持将
和T
转换为ActionResult
ActionResult
转换为T
,表示ObjectResult
简化为返回新的ObjectResult(T)
返回T代码>
ActionResult
并删除products-response属性
总共键入
[HttpGet]
[SwaggerOperation(nameof(GetAnimal))]
[Route("{animalId:long}", Name = nameof(GetAnimal))]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<AnimalModel>> GetAnimal(string tenantId, long animalId) {
try {
// Find the actual animal.. somewhere...using await.
var model = new AnimalModel();
//populate model
return model;
} catch (Exception exception) {
return InternalServerError(new ErrorModel());
}
}
[HttpGet]
[招摇过市操作(名称(GetAnimal))]
[Route(“{animalId:long}”,Name=nameof(GetAnimal))]
[产品响应类型(StatusCodes.Status200OK)]
[产品响应类型(StatusCodes.Status500InternalServerError)]
公共异步任务GetAnimal(字符串tenantId,long animalId){
试一试{
//找到真正的动物…某处…使用等待。
var模型=新的动物模型();
//填充模型
收益模型;
}捕获(异常){
返回InternalServerError(新的ErrorModel());
}
}
或使用新的ActionResult
并删除products-response属性。感谢您的回答(使用wait-fix;)。我试过了:swagger不再列出任何返回类型。
[HttpGet]
[SwaggerOperation(nameof(GetAnimal))]
[Route("{animalId:long}", Name = nameof(GetAnimal))]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<AnimalModel>> GetAnimal(string tenantId, long animalId) {
try {
// Find the actual animal.. somewhere...using await.
var model = new AnimalModel();
//populate model
return model;
} catch (Exception exception) {
return InternalServerError(new ErrorModel());
}
}