【问题标题】:How to return a custom HTTP status/message in ASP.NET Core without returning object, IActionResult, etc?如何在 ASP.NET Core 中返回自定义 HTTP 状态/消息而不返回对象、IActionResult 等?
【发布时间】:2016-11-23 21:48:31
【问题描述】:

我有一个启用了 Swagger 生成和 UI 的 ASP.NET Core Web API 站点。为了让 Swagger 工作(至少自动工作),必须输入控制器方法的返回值。例如,

public async Task<Employee> LoadEmployee(string id)

但是,我需要从此操作返回自定义 HTTP 状态代码和内容。我见过的所有示例都使用 StatusCode 方法,或者返回一些其他对象。这样做的问题是 Swagger 不知道操作的返回类型是什么,因此无法生成 API 规范。

是否有某种方式(异常、控制器上的方法等)返回自定义代码/内容,同时保留签名?我见过使用自定义中间件的解决方案,但这似乎是一个足够常见的场景,应该有一些东西构建它。

【问题讨论】:

    标签: c# asp.net-web-api asp.net-core swagger


    【解决方案1】:

    您可以只使用StatusCodeResult StatusCode(...) 返回状态码和消息/对象。

    public async Task<ObjectResult> LoadEmployee(string id)
    {
        var employee = await repository.GetById(id);
        if(employee == null) {
            return NotFound();
        }
    
        return StatusCode((int)HttpStatusCode.Ok, employee);
    }
    

    【讨论】:

    • 不在 Api 中工作,只有 1 个状态参数,无法传递员工
    【解决方案2】:

    参考:

    ASP.NET Core APIs in the fast lane with Swagger and Autorest

    Adding swagger in ASP.NET Core Web API

    ASP.NET Core 1.0 MVC API documentation using Swashbuckle Swagger

    对于输出定义,只需添加 [Produces][SwaggerResponse] 描述类型的属性 返回,像这样:

    [HttpGet]
    [Produces(typeof(Employee))]
    [SwaggerResponse(System.Net.HttpStatusCode.OK, Type = typeof(Employee))]
    public async Task<IActionResult> LoadEmployee(string id) {
        var employee = await repository.GetById(id);
        if(employee == null) {
            return NotFound();
        }
        return Ok(employee);
    }
    

    【讨论】:

    • 谢谢。我希望避免招摇的特定代码(而不是主要是自我记录的 API),但这有效。
    【解决方案3】:

    ProducesResponseType 属性受 Swagger 支持,是 MVC Web API 核心属性,而不是 Swagger。与SwaggerResponse 相同。

    【讨论】:

      猜你喜欢
      • 2017-05-09
      • 1970-01-01
      • 2017-07-01
      • 2020-04-05
      • 1970-01-01
      • 2019-09-01
      • 2020-05-29
      • 2012-01-07
      • 1970-01-01
      相关资源
      最近更新 更多