【发布时间】:2021-12-22 23:01:33
【问题描述】:
在startup.cs 中,我为所有错误响应添加过滤器,bcs 我通过抛出异常返回自己的错误对象 (ErrorResponse),在中间件中我返回此代码作为响应。但是这些错误不是控制器方法中的返回类型,所以我必须为所有响应添加过滤器。它有效,在 swagger.json 中有这些响应,但没有响应类型 (200),只有错误响应。
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ErrorResponse), (int)HttpStatusCode.BadRequest));
options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ErrorResponse), (int)HttpStatusCode.Unauthorized));
options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ErrorResponse), (int)HttpStatusCode.NotFound));
options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ErrorResponse), (int)HttpStatusCode.InternalServerError));
})
有人知道如何保留控制器方法的默认返回类型吗?
谢谢。 :-)
【问题讨论】:
-
使用
ProducesResponseTypeAttribute或ActionResult<T>作为返回类型 -
我用这个 -
public async Task<ActionResult<HorseEntity>> GetHorseById(int id),在 swagger.json 中不是这些类型,甚至 200 返回
标签: c# asp.net-core swagger