首页 文章

如何在ASP.NET Core中返回自定义HTTP状态/消息而不返回对象,IActionResult等?

提问于
浏览
2

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

public async Task<Employee> LoadEmployee(string id)

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

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

3 回答

  • 3

    引用:

    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);
    }
    
  • 3

    您只需使用 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);
    }
    
  • 1

    Swagger支持 ProducesResponseType 属性,它是MVC Web API Core属性,而不是Swagger . 与 SwaggerResponse 相同 .

相关问题