【问题标题】:swashbuckle openapi 3 write example and description for the dynamically generated model classesswashbuckle openapi 3 为动态生成的模型类编写示例和描述
【发布时间】:2021-05-07 21:19:46
【问题描述】:

我的模型属性定义来自一个 json 文件,因此使用反射来编写要在生成的 swagger 页面上的架构下显示的类。

foreach (var model in Models)
            {
                if (!ModelTypes.ContainsKey(model.Key))
                {
                    anyNonCompiledModel = true;
                    BuildModelCodeClass(modelComponentBuilder, model.Value);//Build model classes
                }
            }
            BuildModelCodeEnd(modelComponentBuilder);

            if (anyNonCompiledModel)
            {
                CSharpCompiler compiler = new CSharpCompiler();
                compiler.AddReference(typeof(object));
                compiler.AddReference(typeof(ResourceFactory));
                compiler.AddReference(typeof(System.Runtime.Serialization.DataContractResolver));
                compiler.AddReference(typeof(System.Runtime.Serialization.DataContractAttribute));
                var types = compiler.Compiler(modelComponentBuilder.ToString()); //write model classes

                foreach (var type in types)
                {
                    ModelTypes.Add(type.Name, type);
                }
            }

public void BuildModelCodeClass(StringBuilder modelComponentBuilder, MetadataModelEntity model)
        {
            
            modelComponentBuilder.AppendLine($"public class {model.Name} {{");

            foreach (var p in model.Data.Properties)
            {
                if (p.Obsoleted) continue;

                if (p.Type.Type == "array")
                {
                    modelComponentBuilder.AppendLine($" public {p.Type.ArrayType.ObjectName}[] {p.Name} {{get;set;}}");
                }
                else
                {
                    //primitive types
                    modelComponentBuilder.AppendLine($" public {p.Type.ObjectName} {p.Name} {{get;set;}}");
                }
            }
            modelComponentBuilder.AppendLine(
@"}
");
            
        }

如果我提供如下描述和示例(在 BuildModelCodeClass 中,循环内),那么示例和描述会显示给我。

if (!string.IsNullOrWhiteSpace((string)p.Example))
                {
                    modelComponentBuilder.AppendLine($" ///<example>{p.Example}</example>");
                }

                if (!string.IsNullOrWhiteSpace((string)p.Description))
                {
                    modelComponentBuilder.AppendLine($" ///<description>{p.Description}</description>");
                }

但是,我不想在上面做。

  1. 我想通过 open api 而不是通过 C# 编译器来编写我的模型,可以吗?

  2. 我想通过模式显示示例和描述(可能在某个地方的路径下)。我怎样才能做到这一点? Context 提供了我可以在此处与之交互的模型信息。

    公共类 SwaggerDocumentFilter : IDocumentFilter { SwaggerDocument _swaggerDocument; 公共 SwaggerDocumentFilter(对象 apiConfigure) { _swaggerDocument = ((ApiGatewayConfiguration)apiConfigure).SwaggerDocument; }

        public void Apply(OpenApiDocument document, DocumentFilterContext context)
        {
            if (document.Info.Extensions == null || !document.Info.Extensions.ContainsKey(SwaggerEndpoint.ExtensionDocName)) return;
    
            var openIdString = document.Info.Extensions[SwaggerEndpoint.ExtensionDocName] as OpenApiString;
            if (openIdString == null) return;
    
            var docName = openIdString.Value;
    
            SwaggerEndpoint endpoint = _swaggerDocument.SwaggerEndpoints.SingleOrDefault(x => x.Name == docName);
            if (endpoint == null) return;
    
    
            //Add server objects
            document.Servers = endpoint.ServerObjects;
    
            //Add Tags objects
            document.Tags = endpoint.Tags;
    
            //Set swagger paths objects
    
            var pathsObjects = _swaggerDocument.GetPathsObject(docName, context);
            if (pathsObjects.IsValid())
            {
                pathsObjects.ToList().ForEach(
                    item => document.Paths.Add(item.Key, item.Value)
                    );
            }
    
            //Add Schema components
            //Add Example/Examples
        }
    
    }
    

【问题讨论】:

    标签: openapi swashbuckle.aspnetcore


    【解决方案1】:

    以下帮助 https://github.com/domaindrivendev/Swashbuckle.WebApi/issues/162

    AddSchemaExamples.cs

    public class AddSchemaExamples : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
            if (type == typeof(Product))
            {
                schema.example = new Product
                    {
                        Id = 123,
                        Type = ProductType.Book,
                        Description = "Treasure Island",
                        UnitPrice = 10.0M
                    };
            }
        }
    }
    

    SwaggerConfig.cs

    httpConfig 
        .EnableSwagger(c =>
             {
                 c.SchemaFilter<AddSchemaExamples>()
             });
    

    由于模型是动态的,因此我的 Apply 实现

    if (model != null)
                    {
                        schema.Description = model.Description;
                        foreach (var p in schema.Properties)
                        {
                            var mp = model.Data.Properties.SingleOrDefault(x => x.Name == p.Key);
                            if (mp != null)
                            {
                                if (!string.IsNullOrWhiteSpace(mp.Description))
                                {
                                    p.Value.Description = mp.Description;
                                }
                                if(!string.IsNullOrWhiteSpace(mp.Example))
                                {
                                    p.Value.Example =
                                        new Microsoft.OpenApi.Any.OpenApiString(mp.Example.ToString());
                                }
                            }
                        }
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 2022-11-10
      • 2019-06-16
      • 2022-10-25
      • 2022-01-07
      • 2018-12-05
      相关资源
      最近更新 更多