如何在 ASP.NET Core 的 Swagger 中包含 XML 注释文件

How to include XML comments files in Swagger in ASP.NET Core

我需要 Swagger 生成 API 文档,包括 UI 来测试操作。

在我的项目中使用ASP.NET时,生成了deps XML个文件,一切正常,如下所示:

但是当我在我的项目中使用ASP.NET Core 时,没有生成deps XML 文件。它只是生成我的项目评论 XML 文件,如下所示:

当我将项目部署到 IIS 时,项目 XML 不在部署文件列表中。

为您依赖的每个项目启用"XML documentation file"复选框以在构建时生成它们的文件。它可以在项目的属性构建选项卡中完成。

要在部署时包含所有 XML 文件,请将此目标添加到已发布项目的 csproj 文件中:

<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
    <ItemGroup>
        <DocFile Include="bin\*\*\*.xml" />
    </ItemGroup>
    <Copy SourceFiles="@(DocFile)" 
          DestinationFolder="$(PublishDir)" 
          SkipUnchangedFiles="false" />
</Target>

这会将所有 XML 文件从 bin 文件夹和嵌套子文件夹(如 bin\Release\netcoreapp1.1\)复制到 publish 目录。当然,您可以自定义该目标。

Microsoft documentation here 建议在您的 csproj 文件中使用 DocumentationFile 标签。

只需确保您的部署构建正确 (Release/Debug):

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <DocumentationFile>bin\Release\netcoreapp2.0\APIProject.xml</DocumentationFile>
</PropertyGroup>

我只是在实践中使用了它(进行了以下调整)并且效果很好:

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
  <DocumentationFile>bin\Release$(TargetFramework)$(MSBuildProjectName).xml</DocumentationFile>
  <NoWarn>1701;1702;1705;1591</NoWarn>
</PropertyGroup>

对于 .Net Core 2 3.1 版本略有不同,对于那些使用较新版本遇到它的人,您可以创建自己的 private void ConfigureSwagger(IServiceCollection services) 构造函数,添加对 swagger services.AddSwaggerGen(c => { c.SwaggerDoc(/*populate with your info */); 的引用,然后定义一个新参数,这将是您的 swagger XML 文档的路径: var filePath = Path.Combine(AppContext.BaseDirectory, "YourApiName.xml"); c.IncludeXmlComments(filePath);.

它应该看起来像这样:

private void ConfigureSwagger(IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "YourApiName",
                Description = "Your Api Description.",
                TermsOfService = "None",
                Contact = new Contact
                    {Name = "Contact Title", Email = "contactemailaddress@domain.com", Url = ""}
            });
            var filePath = Path.Combine(AppContext.BaseDirectory, "YourApiName.xml");
            c.IncludeXmlComments(filePath);
        });
    }

为此,您需要确保构建的输出已检查文档文件(见红色箭头)并正确设置路径。我注意到 你可以删除预填充的路径 并只使用 bin\YourApiName.xml,就像下面这样:

更新:如果这些更改没有按预期工作,请检查配置。在示例中,配置设置为调试。如果您 运行 来自不同的环境 (env),您可能需要检查这些设置是否适用于该环境。

更新 2:自从 OpenAPI 发布以来,我想我会更新我的示例(下面)以显示对 this specification 的更准确引用,它应该遵循类似于:

services.AddSwaggerGen(o =>
            {
                o.SwaggerDoc("v1",
                    new OpenApiInfo
                    {
                        Title = "Your API Name",
                        Description = "Your API Description",
                        Version = "v1",
                        TermsOfService = null, 
                        Contact = new OpenApiContact 
                        {
                            // Check for optional parameters
                        },
                        License = new OpenApiLicense 
                        {
                            // Optional Example
                            // Name = "Proprietary",
                            // Url = new Uri("https://someURLToLicenseInfo.com")
                        }
                    });
            });

在.net core 3.1中,请按照以下步骤操作:

转到Startup.cs页面并添加以下代码

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddSwaggerGen(c => { 
            c.SwaggerDoc("v1", new OpenApiInfo 
            {
            Title="Book Store API",
            Version="v1",
            Description="This is an educational site"});
                var xfile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xpath = Path.Combine(AppContext.BaseDirectory,xfile);
                c.IncludeXmlComments(xpath);
            });
            
            services.AddControllers();
        }

之后转到项目的属性并单击 XML 文档文件选项并保存。

我用这种方式注册XML文件:

  foreach (var filePath in System.IO.Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)), "*.xml"))
                {
                    try
                    {
                        c.IncludeXmlComments(filePath);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }

对于 .Net Core 3.1 和 NuGet xml 文件,我将其添加到项目文件中:

<Project>

  <!-- Here is you other csproj code -->

  <Target Name="_ResolveCopyLocalNuGetPackageXmls" AfterTargets="ResolveReferences">
    <ItemGroup>
      <ReferenceCopyLocalPaths Include="@(ReferenceCopyLocalPaths->'%(RootDir)%(Directory)%(Filename).xml')" Condition="'%(ReferenceCopyLocalPaths.NuGetPackageId)' != '' and Exists('%(RootDir)%(Directory)%(Filename).xml')" />
    </ItemGroup>
  </Target>
</Project>

P.S。这是修改自 https://github.com/ctaggart/SourceLink#known-issues(2.8.3 版本)

的代码

微软自己有这个问题的可用文档here,我发现它很有帮助。

简而言之,需要进行以下更改:

Startup.cs, ConfigureServices()

services.AddSwaggerGen(c =>
{
    ...
    c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"));
});

{project_name}.csproj

<PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>