1.现实swagger IOperationFilter 过滤器接口
public class SwaggerOperationFilter: IOperationFilter
{
private readonly ISchemaGenerator _schemaGenerator;
public SwaggerOperationFilter(ISchemaGenerator schemaGenerator)
{
_schemaGenerator = schemaGenerator;
}
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
// 获取操作返回的类型
var returnType = context.MethodInfo.ReturnType;
// 处理 Task<> 或者 ActionResult<>
if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>))
{
returnType = returnType.GetGenericArguments()[0];
}
// 处理 ActionResult<>
if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(ActionResult<>))
{
returnType = returnType.GetGenericArguments()[0];
}
// 动态给泛型添加接口真实返回的类型
var type = typeof(ApiResponse<>).MakeGenericType(returnType);
// 将描述合并到schema
var schema = _schemaGenerator.GenerateSchema(type, context.SchemaRepository);
operation.Responses.Clear();
operation.Responses.Add("200", new OpenApiResponse
{
Description = "统一的成功响应",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new OpenApiMediaType
{
Schema = schema,
}
}
});
}
}
2.定义返回的泛型类
/// <summary>
/// 全局返回dto
/// </summary>
/// <typeparam name="T"></typeparam>
public class ApiResponse<T>
{
public string Code { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public T Data { get; set; }
}
3.在swagger中使用IOperationFilter现实的过滤
// 注入ISchemaGenerator, 在IOperationFilter实现中构造需要使用
context.Services.AddTransient<ISchemaGenerator>(provider =>
{
var schemaGeneratorOptions = provider.GetRequiredService<SchemaGeneratorOptions>();
var jsonSerializerOptions = provider.GetRequiredService<ISerializerDataContractResolver>();
return new SchemaGenerator(schemaGeneratorOptions, jsonSerializerOptions);
});
context.Services.AddAbpSwaggerGen(options =>
{
// ...................其他代码省略
options.OperationFilter<SwaggerOperationFilter>();
// ...................其他代码省略
});
4.效果展示
接口:
swagger:
标签:get,IAsyncResultFilter,schemaGenerator,var,ui,context,returnType,swagger,public From: https://blog.csdn.net/chinatianmin/article/details/141888993