Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

asp.net core - How to provide sample response in Swagger when using common Response structure?

I am using asp.net core 3.1 with Swashbuckle 5.6. I am using a common class ApiResponse to standardize the response structure. So for both http status codes 404 and 500, my response structure will use same class.

But in the generated swagger documentation, I want to provide different examples for different response codes. If I use typeof(ApiResponse) with either ProducesResponseType or SwaggerResponse, it will end up showing same "Example value" for both 404 and 500 status codes. I tried providing sample in the XML documentation. But that does not come with schema.

ApiResponse class structure is same as that used in below link. https://www.devtrends.co.uk/blog/handling-errors-in-asp.net-core-web-api

public class ApiResponse
{
    public int StatusCode { get; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string Message { get; }

    public ApiResponse(int statusCode, string message = null)
    {
        StatusCode = statusCode;
        Message = message ?? GetDefaultMessageForStatusCode(statusCode);
    }

    private static string GetDefaultMessageForStatusCode(int statusCode)
    {
        switch (statusCode)
        {
            ...
            case 404:
                return "Resource not found";
            case 500:
                return "An unhandled error occurred";
            default:
                return null;
        }
    }
}

Both statusCode and Message will be different for 404 and 500.

I have another similar issue with Ok Response also. By using generics, I am able to get proper example for class type. But for status code and Message, I am unable to provide specific values.

    public class ApiResponseOk<T> : ApiResponse
    {
        public T Result { get; }

        public ApiResponseOk()
        {

        }

        public ApiResponseOk(T result, string message = null)
            : base(200, message)
        {
            Result = result;
        }

    }

Please let me know how can I provide separate examples when using same type for response.

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...