繁体   English   中英

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

[英]How to return a custom HTTP status/message in ASP.NET Core without returning object, IActionResult, etc?

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

public async Task<Employee> LoadEmployee(string id)

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

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

您可以使用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);
}

引用:

使用Swagger和Autorest的快速通道中的ASP.NET Core API

在ASP.NET Core Web API中添加swagger

使用Swashbuckle Swagger的ASP.NET Core 1.0 MVC API文档

对于输出定义,只需添加描述返回类型的[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);
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM