首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swashbuckle覆盖响应类型

Swashbuckle覆盖响应类型
EN

Stack Overflow用户
提问于 2021-06-16 05:52:10
回答 1查看 72关注 0票数 5

我的控制器中有一个通用的Result<T>响应类型,例如

代码语言:javascript
复制
public Result<T> GetSomething()
{
    ...
}

我还有一个自定义的asp.net核心过滤器,它返回T的Json表示

为了让swashbuckle生成正确的文档,我必须用以下内容来修饰每个方法:

代码语言:javascript
复制
[Produces(typeof(T))]

由于这很麻烦,很容易被遗忘,而且容易出错,我一直在寻找一种方法来自动化这一点。

现在在Swashbuckle中你有一个MapType,但是我不能在这些方法中获得T

代码语言:javascript
复制
services.AddSwaggerGen(c =>
{
    ...
    c.MapType(typeof(Result<>), () => /*can't get T here*/);
};

我正在查看IOperationFilter,但我找不到一种方法来覆盖其中的结果类型。

然后是ISchemaFilter

代码语言:javascript
复制
 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);

        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-15 18:05:33

IOperationFilter是正确的选择。下面是一个更改OData端点响应类型的示例。

代码语言:javascript
复制
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方法逐个替换了它们的模式。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67993924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档