[英]How to return a custom HTTP status/message in ASP.NET Core without returning object, IActionResult, etc?
I have an ASP.NET Core Web API site, with Swagger generation and UI enabled. 我有一个ASP.NET Core Web API站点,启用了Swagger生成和UI。 In order for Swagger to work (at least work automatically), the return value from the controller method must be typed.
为了使Swagger工作(至少自动工作),必须输入控制器方法的返回值。 For example,
例如,
public async Task<Employee> LoadEmployee(string id)
However, I need to return custom HTTP status codes and content from this action. 但是,我需要从此操作返回自定义HTTP状态代码和内容。 All the examples I've seen use the StatusCode method, or return some other object.
我见过的所有示例都使用StatusCode方法,或者返回其他一些对象。 The problem with this is then Swagger doesn't know what the return type of the action is, and so can't generate the API spec.
这个问题就是Swagger不知道动作的返回类型是什么,因此无法生成API规范。
Is there some way (Exception, methods on controller, etc) to return the custom code/content, while keeping the signature? 是否有某种方式(异常,控制器上的方法等)返回自定义代码/内容,同时保持签名? I've seen solutions using custom middleware, but it seems like a common enough scenario that there should be something built it.
我见过使用自定义中间件的解决方案,但似乎应该有一些内置的东西。
You can just use StatusCodeResult StatusCode(...)
to return status code and a message/object. 您可以使用
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);
}
references: 引用:
ASP.NET Core APIs in the fast lane with Swagger and Autorest 使用Swagger和Autorest的快速通道中的ASP.NET Core API
Adding swagger in ASP.NET Core Web API 在ASP.NET Core Web API中添加swagger
ASP.NET Core 1.0 MVC API documentation using Swashbuckle Swagger 使用Swashbuckle Swagger的ASP.NET Core 1.0 MVC API文档
For output definition, just add the
[Produces]
and[SwaggerResponse]
attributes describing the Type returned, like this:对于输出定义,只需添加描述返回类型的
[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);
}
ProducesResponseType
attribute is supported by Swagger and is a MVC Web API Core attribute, not Swagger. Swagger支持
ProducesResponseType
属性,它是MVC Web API Core属性,而不是Swagger。 Does the same as SwaggerResponse
. 与
SwaggerResponse
相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.