使用 Asp.net core 的 Swashbuckle 如何将通用类型的响应添加到生成的模型列表中?

问题描述 投票:0回答:1

我有以下 Response 对象:

    public class Response<T> where T : ResponseData
    {

        public bool Success { get; set; }
        public HttpStatusCode StatusCode { get; set; }
        public string ErrorCode { get; set; }
        public string ErrorDescription { get; set; }
        public T Data { get; set; }

        public Response(bool success, HttpStatusCode statusCode, string errorCode, string msg, T data = null)
        {
            Success = success;
            StatusCode = statusCode;
            ErrorCode = errorCode;
            ErrorDescription = msg;
            Data = data;
        }

ResponseData 类只是一个基类:

    public class ResponseData
    {
    }

然后我有以下课程:

    public class ResponseProduct: ResponseData
    {
        public int Id{ get; set; }

        public string Description { get; set; }
    }

我的控制器上有以下内容:

        [HttpGet]
        [Route(ApiBaseConstants.MethodProduct)]
        [Consumes(MediaTypeNames.Application.Json)]
        [ProducesResponseType(typeof(Response<ResponseProduct>), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetProduct()
        {
            return ParseResponse(await CurrentApi.GetProduct());
        }

我遇到的问题是它不会在模式上生成 Response 对象,而是生成一个 ResponseProductResponse ,它是 Response< ResponseProduct > 所以我有以下模式:

  • 响应数据
  • 回复产品
  • 回复产品回复

如何获得 Response 而不是 ResponseProductResponse?

c# asp.net-core swagger swashbuckle.aspnetcore
1个回答
0
投票

好吧,添加 SchemaFilter 就可以了

public class ResponseTypeSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (context.Type.IsGenericType && context.Type.GetGenericTypeDefinition() == typeof(Response<>))
        {
            var responseType = context.Type.GetGenericArguments()[0];

            if (responseType.IsGenericType && responseType.GetGenericTypeDefinition() == typeof(List<>))
            {
                var itemType = responseType.GetGenericArguments()[0];
                var itemSchema = context.SchemaGenerator.GenerateSchema(itemType, context.SchemaRepository);
                schema.Type = "array";
                schema.Items = itemSchema;
            }
            else
            {
                schema.Reference = null;
                schema.Properties.Clear();
                schema.Type = "object";
                var props = responseType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (var prop in props)
                {
                    schema.Properties[prop.Name] = context.SchemaGenerator.GenerateSchema(prop.PropertyType, context.SchemaRepository);
                }
            }
        }
    }
}

并像这样配置你的招摇

services.AddSwaggerGen(swaggerOptions =>
        {
            swaggerOptions.SchemaFilter<ResponseTypeSchemaFilter>();

        });
© www.soinside.com 2019 - 2024. All rights reserved.