【发布时间】: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>");
}
但是,我不想在上面做。
-
我想通过 open api 而不是通过 C# 编译器来编写我的模型,可以吗?
-
我想通过模式显示示例和描述(可能在某个地方的路径下)。我怎样才能做到这一点? 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