使用通用响应结构时如何在 Swagger 中提供示例响应?

问题描述

我使用的是带有 Swashbuckle 5.6 的 asp.net core 3.1。我正在使用一个通用类 ApiResponse 来标准化响应结构。因此,对于 http 状态代码 404 和 500,我的响应结构将使用相同的类。

但是在生成的swagger文档中,我想为不同的响应代码提供不同的示例。如果我将 typeof(ApiResponse) 与 ProducesResponseType 或 SwaggerResponse 一起使用,它最终会为 404 和 500 状态代码显示相同的“示例值”。我尝试在 XML 文档中提供示例。但这并不伴随架构。

ApiResponse 类结构与以下链接中使用的相同。 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;
        }
    }
}

404 和 500 的 statusCode 和 Message 将不同。

我也有一个与 Ok Response 类似的问题。通过使用泛型,我可以获得类类型的正确示例。但对于状态码和消息,我无法提供具体值。

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

        public ApiResponseOk()
        {

        }

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

    }

请让我知道在使用相同类型的响应时如何提供单独的示例。

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...