fingers10
fingers10

Reputation: 7987

How to document a wrapped response to be displayed in swagger ui using a Swashbuckle in asp.net core web api

I working on a ASP.NET Core 3.1 web api project. I'm using Swashbuckle.AspNetCore 5.0.0 for documenting my API. Things are working good. However I got stuck with generating response types as my api is using an middleware to wrap every response for consistency. I'm not able to generate correct response type in my swagger ui.

Here is an simple example,

My Action Method:

[HttpGet]
[ProducesResponseType(200, Type = typeof(IEnumerable<WeatherForecast>))]
public IEnumerable<WeatherForecast> Get()
...

As I mentioned, the project has response middleware which will wrap all the response as shown in the below format,

{  
    "Version": "1.0.0.0",  
    "StatusCode": 200,  
    "Message": "Request successful.",  
    "Result": [  
        "value1",  
        "value2"  
    ]  
}    

Because of this I'm getting mismatch in response value in my swagger ui.

Example of response schema shown in swagger ui as per [ProducesResponseType(200, Type = typeof(IEnumerable<WeatherForecast>))]

enter image description here

But the actual wrapped response looks like,

enter image description here

Is it possible to handle these wrapped response using Swashbuckle.AspNetCore 5.0.0. Please assist me.

Upvotes: 0

Views: 2459

Answers (1)

fingers10
fingers10

Reputation: 7987

After some analysis and research, I found the solution. It's pretty simple using the [ProducesResponseType] attribute.

I created a separate class named ResponseWrapper<T>,

public class ResponseWrapper<T>
{
    public int StatusCode { get; set; }

    public string Message { get; set; }

    public T Result { get; set; }
}

And then decorated my action method as follows,

[HttpGet]
[ProducesResponseType(200, Type = typeof(ResponseWrapper<IEnumerable<WeatherForecast>>))]
public IEnumerable<WeatherForecast> Get()
...

And that works. Hope this helps someone.

Upvotes: 4

Related Questions