skip to Main Content

How can I set swagger to shown all possible responses?

Now only shows the HTTP 200, but there are more possible responses
I have a global exception handling class and I would like to a global solution.

Response

Nothing, but now i will try some possible solutions.

If i use it:

[ProducesResponseType(200)]
[ProducesResponseType(401)]
[ProducesResponseType(404)]

at controller method it is work and swagger shows more possible responses. But i would like to a global solution

Is there a swagger settings or something else?

3

Answers


  1. Chosen as BEST ANSWER

    So https://stackoverflow.com/users/113116/helen find the correct and beauty solution.

    Swashbuckle general response codes

    Is a way to declare common response types to different actions?

    What i used for general response handling: /in AddSwaggerGen

    options.OperationFilter<GeneralExceptionOperationFilter>();
    

    .

    internal class GeneralExceptionOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            operation.Responses.Add("401", new OpenApiResponse() { Description = "Unauthorized" });
            operation.Responses.Add("403", new OpenApiResponse() { Description = "Forbidden" });
    
            //Example where we filter on specific HttpMethod and define the return model
            var method = context.MethodInfo.GetCustomAttributes(true)
                .OfType<HttpMethodAttribute>()
                .Single();
    
            if (method is HttpDeleteAttribute || method is HttpPostAttribute || method is HttpPatchAttribute || method is HttpPutAttribute)
            {
                operation.Responses.Add("409", new OpenApiResponse()
                {
                    Description = "Conflict",
                    Content = new Dictionary<string, OpenApiMediaType>()
                    {
                        ["application/json"] = new OpenApiMediaType
                        {
                            Schema = context.SchemaGenerator.GenerateSchema(typeof(string), context.SchemaRepository)
                        }
                    }
                });
            }
        }
    }
    

  2. If you add the following attributes to the methods you can specify the output model and the error

    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(YOUROBJECT))]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    
    Login or Signup to reply.
  3. Just an additional info, specifically for java and springboot based apps, we need use combination of @RestControllerAdvice and @ResponseStatus annotations.

    Step 1: Add @RestControllerAdvice on GlobalExceptionHandler

    Step 2: Add @ResponseStatus(HTTPStatus.INTERNAL_SERVICE_ERROR) on
    each method that you have handled and want to show.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search