简体   繁体   中英

Set a different media type for 401 error code using Swashbuckle

Is it possible to configure Swashbuckle to produce a different media type for a specific HTTP error code 401 in Swagger UI?

在此处输入图像描述

I want the media type for the 400 error code to be application/JSON, but for 401, it is text/HTML. Is there a way to achieve this?

Annotations above controller,

[Authorize]
[ApiController]
[ApiVersion("1.0")]
[Route("[controller]")]
[Route("v{version:apiVersion}/[controller]")]
[Produces("application/json")]
public class MyController : ControllerBase
{
}

Annotations above my method,

    [ProducesResponseType(StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status401Unauthorized)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    [HttpPost]
    public async Task<ActionResult<MyModel>> PostAsync(MyRequest myRequest)
    {
}

Have you tried SwaggerResponse attribute, it derives from ProducesResponseType and has been enhanced to support adding the content media type:

    [SwaggerResponse(StatusCodes.Status201Created, "Successfully created something", typeof(MyModel), "application/json")]
    [SwaggerResponse(StatusCodes.Status401Unauthorized, "Unauthorized", typeof(string), "text/html")]
    [SwaggerResponse(StatusCodes.Status400BadRequest, "Invalid request", typeof(string), "text/html")]
    [SwaggerResponse(StatusCodes.Status500InternalServerError, "Internal Server Error", typeof(string), "text/html")]

It is part of the nuget package: Swashbuckle.AspNetCore.Annotations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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