我的控制器中有一个通用的Result<T>响应类型,例如
public Result<T> GetSomething()
{
...
}我还有一个自定义的asp.net核心过滤器,它返回T的Json表示
为了让swashbuckle生成正确的文档,我必须用以下内容来修饰每个方法:
[Produces(typeof(T))]由于这很麻烦,很容易被遗忘,而且容易出错,我一直在寻找一种方法来自动化这一点。
现在在Swashbuckle中你有一个MapType,但是我不能在这些方法中获得T:
services.AddSwaggerGen(c =>
{
...
c.MapType(typeof(Result<>), () => /*can't get T here*/);
};我正在查看IOperationFilter,但我找不到一种方法来覆盖其中的结果类型。
然后是ISchemaFilter
public class ResultSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (!context.Type.IsGenericType || !context.Type.GetGenericTypeDefinition().IsAssignableFrom(typeof(Result<>)))
{
return;
}
var returnType = context.Type.GetGenericArguments()[0];
//How do I override the schema here ?
var newSchema = context.SchemaGenerator.GenerateSchema(returnType, context.SchemaRepository);
}
}发布于 2021-11-15 18:05:33
IOperationFilter是正确的选择。下面是一个更改OData端点响应类型的示例。
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
//EnableQueryAttribute refers to an OData endpoint.
if (context.ApiDescription.ActionDescriptor.EndpointMetadata.Any(em => em is EnableQueryAttribute))
{
//Fixing the swagger response for Controller style endpoints
if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor cad)
{
//If the return type is IQueryable<T>, use ODataResponseValue<T> as the Swagger response type.
var returnType = cad.MethodInfo.ReturnType;
if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(IQueryable<>))
{
var actualType = returnType.GetGenericArguments()[0];
var responseType = typeof(ODataResponseValue<>).MakeGenericType(actualType);
var schema = context.SchemaGenerator.GenerateSchema(responseType, context.SchemaRepository);
foreach (var item in operation.Responses["200"].Content)
item.Value.Schema = schema;
}
}
}
}正如您在这里看到的,我遍历了operation.Responses["200"].Content中的所有项,使用您找到的GenerateSchema方法逐个替换了它们的模式。
https://stackoverflow.com/questions/67993924
复制相似问题