gpt4 book ai didi

c# - SwaggerUI 不显示枚举摘要描述,C# .net 核心?

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:56 24 4
gpt4 key购买 nike

我用了https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.1&tabs=visual-studio#xml-comments在 SwaggerUI 中显示我的类摘要描述,没关系,但不显示 enum 摘要描述!
我的startup.cs

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "My App-Service",
Description = "My Description",
});
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"));
c.DescribeAllEnumsAsStrings();
});

我的枚举:

public enum GenderEnum
{
/// <summary>
/// Man Description
/// </summary>
Man = 1,

/// <summary>
/// Woman Description
/// </summary>
Woman = 2
}

它显示如下内容:
Swagger UI enum

我想在 SwaggerUI 中显示 Man DescriptionWoman Description
像这样:

Man = 1, Man Description
Woman = 2, Woman Description


我正在使用 Swashbuckle.AspNetCore v4.0.1

最佳答案

截至 2021 年 6 月,OpenApi 现在支持此功能,您可以扩展 Swagger 以显示详细信息。这是我在 .NET 5.0 上的 C# 代码。

首先在文件中定义架构过滤器(将其命名为 DescribeEnumMembers.cs 并确保将 YourNamespace 更改为您的命名空间的名称):

using System;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;

using Microsoft.OpenApi.Models;

using Swashbuckle.AspNetCore.SwaggerGen;

namespace YourNamespace
{
/// <summary>
/// Swagger schema filter to modify description of enum types so they
/// show the XML docs attached to each member of the enum.
/// </summary>
public class DescribeEnumMembers: ISchemaFilter
{
private readonly XDocument mXmlComments;

/// <summary>
/// Initialize schema filter.
/// </summary>
/// <param name="argXmlComments">Document containing XML docs for enum members.</param>
public DescribeEnumMembers(XDocument argXmlComments)
=> mXmlComments = argXmlComments;

/// <summary>
/// Apply this schema filter.
/// </summary>
/// <param name="argSchema">Target schema object.</param>
/// <param name="argContext">Schema filter context.</param>
public void Apply(OpenApiSchema argSchema, SchemaFilterContext argContext) {
var EnumType = argContext.Type;

if(!EnumType.IsEnum) return;

var sb = new StringBuilder(argSchema.Description);

sb.AppendLine("<p>Possible values:</p>");
sb.AppendLine("<ul>");

foreach(var EnumMemberName in Enum.GetNames(EnumType)) {
var FullEnumMemberName = $"F:{EnumType.FullName}.{EnumMemberName}";

var EnumMemberDescription = mXmlComments.XPathEvaluate(
$"normalize-space(//member[@name = '{FullEnumMemberName}']/summary/text())"
) as string;

if(string.IsNullOrEmpty(EnumMemberDescription)) continue;

sb.AppendLine($"<li><b>{EnumMemberName}</b>: {EnumMemberDescription}</li>");
}

sb.AppendLine("</ul>");

argSchema.Description = sb.ToString();
}
}
}

然后在您的 ASP.NET ConfigureServices() 方法中启用它。这是我在删除与本练习无关的部分后的代码:

public void ConfigureServices(IServiceCollection argServices) {
// ...<snip other code>

argServices.AddSwaggerGen(SetSwaggerGenOptions);

// ...<snip other code>

return;

// ...<snip other code>

void SetSwaggerGenOptions(SwaggerGenOptions argOptions) {
// ...<snip other code>

AddXmlDocs();
return;

void AddXmlDocs() {
// generate paths for the XML doc files in the assembly's directory.
var XmlDocPaths = Directory.GetFiles(
path: AppDomain.CurrentDomain.BaseDirectory,
searchPattern: "YourAssemblyNameHere*.xml"
);

// load the XML docs for processing.
var XmlDocs = (
from DocPath in XmlDocPaths select XDocument.Load(DocPath)
).ToList();

// ...<snip other code>

// add pre-processed XML docs to Swagger.
foreach(var doc in XmlDocs) {
argOptions.IncludeXmlComments(() => new XPathDocument(doc.CreateReader()), true);

// apply schema filter to add description of enum members.
argOptions.SchemaFilter<DescribeEnumMembers>(doc);
}
}
}
}

请记住更改 "YourAssemblyNameHere*.xml" 以匹配您的程序集名称。启用架构过滤器的重要行是:

argOptions.SchemaFilter<DescribeEnumMembers>(doc);

...必须在以下行之后调用:

argOptions.IncludeXmlComments(() => new XPathDocument(doc.CreateReader()), true);

使用上面的代码,如果你有一个这样定义的枚举类型,例如:

  /// <summary>
/// Setting to control when a no-match report is returned when searching.
/// </summary>
public enum NoMatchReportSetting
{
/// <summary>
/// Return no-match report only if the search query has no match.
/// </summary>
IfNoMatch = 0,
/// <summary>
/// Always return no-match report even if the search query has a match.
/// </summary>
Always = 1,
/// <summary>
/// Never return no-match report even if search query has no match.
/// </summary>
No = 99
}

Swagger 文档最终将显示每个枚举成员的描述,作为枚举类型本身描述的一部分:

swagger doc screenshot

关于c# - SwaggerUI 不显示枚举摘要描述,C# .net 核心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53282170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com