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

8

37

I need Swagger generate API documentation include UI to test operations.

When use ASP.NET in my project, deps XML files are generated, everything is OK, look like this:

enter image description here

But when I use ASP.NET Core in my project, deps XML files are not generated. It just generates my project comments XML file, look like this:

enter image description here

And when I deploy my project to IIS, the project XML not in deploy files list.

Spinner answered 20/6, 2017 at 3:4 Comment(1)
did you remember to include <GenerateDocumentationFile>true</GenerateDocumentationFile> in all of your .csproj files? You also need to add each assembly inside .AddSwaggerGen.Quilmes
C
18

Enable "XML documentation file" checkbox for each project you depend on to generate their files on build. It could be done at project's properties Build tab.

To include all XML files on deploy, add this target to the published project's csproj file:

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

This will copy all XML files from bin folder and nested subfolders (like bin\Release\netcoreapp1.1\) to publish dir. Of course you can customize that target.

Caryloncaryn answered 20/6, 2017 at 6:54 Comment(2)
You shouldn't need the custom script for copying XML files, simply checking the "XML documentation file" should be enough to do that. Just make sure you do that for all Configurations, not just a specific one (e.g. Debug).Aubrey
@SaebAmini You are both right.Indihar
S
54

For .Net Core 2 up to 8* versions it's slightly different, for those who come across it using a newer version you would create your private void ConfigureSwagger(IServiceCollection services) constructor, add the reference to swagger services.AddSwaggerGen(c => { c.SwaggerDoc(/*populate with your info */); then define a new parameter which will be the path for your swagger XML documentation: var filePath = Path.Combine(AppContext.BaseDirectory, "YourApiName.xml"); c.IncludeXmlComments(filePath);.

It should look something like this:

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 = "[email protected]", Url = ""}
            });
            var filePath = Path.Combine(AppContext.BaseDirectory, "YourApiName.xml");
            c.IncludeXmlComments(filePath);
        });
    }

For this to work, you need to ensure that the build's Output has the documentation file checked (see red arrow) and the path set appropriately. I've noticed that you can strip the pre-filled path and just use bin\YourApiName.xml, just like below:

Image showing how to enable XML documentation in Visual Studio 2017 IDE

Update: If these changes aren't working as expected, please check the configuration. In the example, the config is set to Debug. If you're running from a different environment (env) you may need to check whether these setting apply to that env.

Update 2: Since the release of OpenAPI I thought I'd update my example (below) to show a more accurate reference to this specification which should follow something similar to:

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")
                        }
                    });
            });

Update 3: Thank you to comments from the community keeping this post updated within compatible versions. *Swashbuckle.AspNetCore (AKA Swagger) is being removed in .NET 9.

Suki answered 21/12, 2018 at 14:39 Comment(2)
Absolutely valid for .NET 7Ultimate
Mostly valid for .NET 8 and VS 2022 as well, although the Output setting looks slightly different.Sefton
C
18

Enable "XML documentation file" checkbox for each project you depend on to generate their files on build. It could be done at project's properties Build tab.

To include all XML files on deploy, add this target to the published project's csproj file:

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

This will copy all XML files from bin folder and nested subfolders (like bin\Release\netcoreapp1.1\) to publish dir. Of course you can customize that target.

Caryloncaryn answered 20/6, 2017 at 6:54 Comment(2)
You shouldn't need the custom script for copying XML files, simply checking the "XML documentation file" should be enough to do that. Just make sure you do that for all Configurations, not just a specific one (e.g. Debug).Aubrey
@SaebAmini You are both right.Indihar
C
15

I use this way to register XML file:

  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);
                    }
                }
Crosby answered 16/9, 2020 at 9:48 Comment(2)
worked a treat for me having controllers in multiple projects referenced by a single, main api projectHyps
This is the way.Pietro
I
14

For .Net Core 3.1 and NuGet xml files I add this to project file:

<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. This is modified code from https://github.com/ctaggart/SourceLink#known-issues (2.8.3 version)

Idun answered 22/9, 2020 at 9:23 Comment(2)
This actually works when building locally. Do note that if you build in a Docker context you might have to add ENV NUGET_XMLDOC_MODE=none to get the xml files included.Masonry
The only solution that works. Thanks a lot, Vlad!!!Breann
B
10

Microsoft themselves have documentation for this question available here, I found it quite helpful.

In short, the following changes are required:

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>
Burwell answered 15/11, 2021 at 13:55 Comment(0)
S
3

The Microsoft documentation here suggests using a DocumentationFile tag in your csproj file.

Just make sure you have the correct build for your deployment (Release/Debug):

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

I just used this in practice (with the tweaks below) and it works well:

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
  <DocumentationFile>bin\Release\$(TargetFramework)\$(MSBuildProjectName).xml</DocumentationFile>
  <NoWarn>1701;1702;1705;1591</NoWarn>
</PropertyGroup>
Sashenka answered 23/5, 2018 at 13:28 Comment(0)
S
2

For .Net 7, in your project file, add:

<PropertyGroup>
    ...
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

In your Program.cs file, add:

builder.Services.AddSwaggerGen(c =>
{
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
Shutout answered 5/10, 2023 at 15:59 Comment(0)
F
1

In .net core 3.1,Please follow the below steps:

Go to Startup.cs Page and add the below code

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();
        }

After that go to Properties of the project and click on the XML Documentation File option and save it. enter image description here

Fashion answered 14/8, 2020 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.