如何在 swagger/swashbuckle WebAPI 2 中定义响应错误元数据

How to define response error metadata in swagger/swashbuckle WebAPI 2

我已经弄清楚如何在 swashbuckle 中创建响应对象元数据:

[Route("X/{Y:Guid}")]
[HttpGet]
[SwaggerResponse(HttpStatusCode.OK, "Bla", typeof(BlaDto))]
public IHttpActionResult GetSomething([FromUri] Guid someGuid)
{
    Bla returnObject;
    try
    {
        returnObject = _service.Get(someGuid);
    }
    catch (DatabaseException databaseException)
    {
        ModelState.AddModelError("DatabaseException", databaseException.Message);
        return BadRequest(ModelState);
    }

    return Ok(returnObject);     
}

我仍在寻找示例来定义请求对象元数据和 400 错误等的元数据。任何指针将不胜感激。

操作的对象元数据由 Swashbuckle 自动检测。可以通过添加更多 SwaggerResponseAttribute 来指定错误的对象元数据。

这是一个例子:

[Route("X}")]
[HttpPost]
[SwaggerResponse(HttpStatusCode.Created, "Bla", typeof(BlaDto))]
[SwaggerResponse(HttpStatusCode.Conflict, Type = typeof(ErrorResponse))]
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(ErrorResponse))]
public IHttpActionResult CreateBla(BlaDto bla)
{
    BladDto returnObject;

    try
    {
        returnObject = _service.Create(bla);
    }
    catch (DatabaseException databaseException)
    {
        var error = new ErrorResponse { Message = databaseException.Message);
        return Content(HttpStatusCode.BadRequest, error);
    }
    catch (SomeOtherException ex)
    {
        var error = new ErrorResponse { Message = ex.Message);
        return Content(HttpStatusCode.Conflict, error);
    }
    return Ok(returnObject);     
}

public class ErrorResponse
{
    string Message { get; set; }
}