SwashBuckle定义Error Body on Error

时间:2017-03-23 11:19:33

标签: c# asp.net-core swagger swashbuckle

我的应用程序是ASP.NET Core 1.0 Web API。

我有以下控制器:

    [HttpGet("{someData:MinLength(5):MaxLength(5)}")]
    [Produces("application/json")]
    public async Task<IActionResult> GetSomeData(string someData)
    {
        return this.Ok(JsonConvert.SerializeObject("Data is: " + someData));
    }

每当我传递字符串“111”时,swagger会向我显示以下消息:

enter image description here

我如何能够像以下一样成为响应机构:

“请输入5个数字”

谢谢

2 个答案:

答案 0 :(得分:5)

您可以使用[ProducesResponseType(typeof(ModelStateDictionary), (int)HttpStatusCode.OK)]注释您的操作,以返回典型的字典类型错误消息,例如使用return BadRequest(ModelState)时。

但是您无法在架构定义中返回文本。它适用于json结构,而不适用于错误消息。相反,你应该使用xmldoc(并在swagger中启用它)来为参数添加描述。

更新:添加参数文档及其含义的替代方法

/// <summary>
/// Returns some data based on <paramref name="someData"/> parameter.
/// </summary>
/// <param name="someData">Some data. (Must be exactly 5 characters wide)</param>
/// <response code="200">Returns indexed tags on success</response>
/// <response code="400">Invalid data sent</response>
/// <returns>A paged list of results</returns>
[HttpGet("{someData:MinLength(5):MaxLength(5)}")]
[ProducesResponseType(typeof(MyReturnType), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetSomeData(string someData)
{
}

您还需要在项目的属性中启用xmldocs的构建。

并添加到您的创业公司:

services.AddSwaggerGen(options =>
{
    ...
    var appEnv = PlatformServices.Default.Application;

    options.IncludeXmlComments(Path.Combine(appEnv.ApplicationBasePath, $"{appEnv.ApplicationName}.xml"));
    ...
});

答案 1 :(得分:1)

我正在使用ApiBadRequestResponse类,该类从modelState而不是直接ModelState构造字符串列表。 该类是从不错的文章https://www.devtrends.co.uk/blog/handling-errors-in-asp.net-core-web-api复制而来的。

使用示例:

 [ProducesResponseType(typeof(ApiBadRequestResponse), (int)HttpStatusCode.BadRequest)]
 public async Task<IActionResult> GetSomeData(string someData)
 {
   return BadRequest(new ApiBadRequestResponse(ModelState));
 }

实现(基类描述为in the article):

/// <summary>
    ///  an ApiBadRequestResponse class to handle validation errors from modelState or exception.
    /// </summary>
    public class ApiBadRequestResponse : ApiResponse
    {
        public IEnumerable<string> Errors { get; }

        public ApiBadRequestResponse(ModelStateDictionary modelState)
            : base(HttpStatusCode.BadRequest) //400)
        {
            if (modelState.IsValid)
            {
                throw new ArgumentException("ModelState must be invalid", nameof(modelState));
            }

            Errors = modelState.SelectMany(x => x.Value.Errors)
                .Select(x => x.ErrorMessage).ToArray();
        }

        public ApiBadRequestResponse(Exception exception, string message=null)
            : base(HttpStatusCode.BadRequest, message) //400)
        {
            Errors = new List<string>() {exception.ToString()};
        }
    }

http://www.khalidabuhakmeh.com/a-better-validation-result-for-asp-net-webapi

中是另一个类似的解决方案