c# - 自动生成的 c# 客户端应该如何处理可以返回不同类型的 API 调用?

标签 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.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());
    }    
}

这似乎导致 autorest 生成一个以 object 作为返回类型的 C# 客户端(我猜是因为 ProducesResponseType 属性被指定两次):

public async Task<HttpOperationResponse<object>> GetAnimalWithHttpMessagesAsync(string tenantId, long animalId, [..])

问题

处理返回不同对象的 API 的推荐方法是什么?

可能的解决方案

  • 我可以修复客户端代码并转换结果以找到正确的类型(不好)。
  • 我可以修改 API(如果可能),使其仅返回一个由 AnimalModelErrorModel 组成的对象(可能会更好)。

最佳答案

ActionResult<T>

ASP.NET Core 2.1 introduces the ActionResult<T> return type for Web API controller actions. It enables you to return a type deriving from ActionResult or return a specific type. ActionResult<T> offers the following benefits over the IActionResult type:

  • The [ProducesResponseType] attribute's Type property can be excluded. For example, [ProducesResponseType(200, Type = typeof(Product))] is simplified to [ProducesResponseType(200)]. The action's expected return type is instead inferred from the T in ActionResult<T>.
  • Implicit cast operators support the conversion of both T and ActionResult to ActionResult<T>. T converts to ObjectResult, which means return new ObjectResult(T); is simplified to return T;.

考虑使用新的 ActionResult<T>并删除 produces 响应属性 Type完全。

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

关于c# - 自动生成的 c# 客户端应该如何处理可以返回不同类型的 API 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51637214/

相关文章:

java - 如何 Swagger 注释具有复杂对象的 Spring GET @RequestMapping

c# - 为什么 WeakReference.IsAlive 变为假?

c# - 如何将连接字符串从startup.cs asp.net core传递到UnitOfWork项目

azure - 生成本地运行的用户委托(delegate) SAS token

amazon-web-services - Windows Server 2016 上的 Linux Docker 容器在 AWS 中构建服务器

c# - 使用 Swagger 向端点添加注释

java - 如何在没有注释的情况下使用swagger

c# - 使用反射设置值 - 转换错误

c# - InvalidOperationException : No authentication handler is registered for the scheme 'CookieSettings' . 是否忘记调用 AddAuthentication()

c# - 当将一个类从 c# 编码到 native c++ 时,它会克隆吗?