用Swashbuckle生成Swagger文档时,如何将泛型类型替换为具体类型?

bq3bfh9z  于 2023-01-30  发布在  其他
关注(0)|答案(1)|浏览(182)

我的操作装饰有:

[ProducesResponseType(typeof(ValidationException<ErrorEnum>), StatusCodes.Status400BadRequest)]

我需要将生成的响应更改为不同的类型,因此我添加了一个操作过滤器:

public class ValidationExceptionFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor cad)
        {
            var returnType = cad.MethodInfo.ReturnType;
            if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(ValidationException<>))
            {
                var schema = context.SchemaGenerator.GenerateSchema(typeof(ValidationExceptionDto), context.SchemaRepository);
                foreach (var item in operation.Responses["400"].Content)
                    item.Value.Schema = schema;
            }
        }
    }
}

但是在生成swagger json时泛型类型并没有被替换,我在这里遗漏了什么?

q35jwt9p

q35jwt9p1#

使用这一行,你将得到方法的返回类型:

var returnType = cad.MethodInfo.ReturnType;

例如,控制器如:

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

您将获得IEnumerable WeatherForecast类型,而不是Some或WeatherForecast类型
我尝试获取方法上的ProducesResponseTypeAttribute并访问Type属性:

public class ValidationExceptionFilter : IOperationFilter    
    {        
        public void Apply(OpenApiOperation operation, OperationFilterContext context)        
        {            
        if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor cad)            
        {                
        var attrs=cad.MethodInfo.GetCustomAttributes(typeof(ProducesResponseTypeAttribute),true);                
        foreach(var attr in attrs)              
        {                   
          if((attr as ProducesResponseTypeAttribute).Type.IsGenericType&& (attr as ProducesResponseTypeAttribute).Type.GetGenericTypeDefinition()==typeof(Some<>))                    {                       
         var schema = context.SchemaGenerator.GenerateSchema(typeof(SomeDto), context.SchemaRepository);                        
        foreach (var item in operation.Responses["400"].Content)                            
        item.Value.Schema = schema;                    
        }                
      }            
     }        
   }    
 }

响应类型已修改:

json文件:

相关问题