Adding Method Descriptions to Swagger UI in WebAPI Applications: A Guide to XML Comments and Swashbuckle Configuration

Dec 07, 2025 · Programming · 10 views · 7.8

Keywords: Swagger UI | XML Comments | Swashbuckle Configuration

Abstract: This article provides a comprehensive guide on adding method descriptions to Swagger UI in ASP.NET Core WebAPI applications using XML comments and Swashbuckle configuration. It covers enabling XML documentation generation, configuring Swashbuckle to include XML comments, annotating controller actions and models with XML tags, and using SwaggerOperation attributes as a supplementary approach. The article also discusses the distinction between HTML tags and characters, offering complete code examples and step-by-step instructions to generate detailed API documentation.

In RESTful API development, Swagger UI is a widely-used tool for automatically generating interactive documentation, enhancing development efficiency and user experience. However, default-generated documentation may lack detailed method descriptions, reducing its readability and utility. Based on the Swashbuckle.AspNetCore library, this article explores how to add method descriptions to Swagger UI through XML comments and configuration, improving the clarity and functionality of API documentation.

Enabling XML Documentation Generation

First, enable the generation of XML documentation files in the project. Open the project properties dialog, click the "Build" tab, and ensure the "XML documentation file" option is checked. This will generate a file containing all XML comments at build time. Note that if some classes or methods are not annotated with XML comments, build warnings (code 1591) may be triggered. To suppress these warnings, enter "1591" in the "Suppress warnings" field. This step is foundational, as subsequent Swagger configuration relies on this XML file to extract comment information.

Configuring Swashbuckle to Include XML Comments

In the ConfigureServices method of the Startup class, configure Swashbuckle to include the generated XML comments file. Here is an example code snippet:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1",
        new OpenApiInfo
        {
            Title = "My API - V1",
            Version = "v1"
        }
     );

     var filePath = Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml");
     c.IncludeXmlComments(filePath);
});

Here, the IncludeXmlComments method specifies the path to the XML file, typically located in the application's base directory. If the project includes multiple XML comment files (e.g., controllers and models in separate libraries), this method can be invoked multiple times, and all comments will be merged into the generated Swagger JSON.

Annotating Controller Actions and Models with XML Tags

To provide detailed method descriptions, use XML comment tags to annotate controller actions. For example, for an API method that retrieves a product, add the following comments:

/// <summary>
/// Retrieves a specific product by unique ID
/// </summary>
/// <remarks>This is an example remark for additional information.</remarks>
/// <response code="200">Product successfully retrieved</response>
/// <response code="400">Invalid product ID or missing values</response>
/// <response code="500">Internal server error, unable to retrieve product</response>
[HttpGet("{id}")]
[ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(500)]
public Product GetById(int id)
{
    // Method implementation
}

Here, the <summary> tag provides a brief description of the method, <remarks> adds extra notes, and <response> tags define response descriptions for different HTTP status codes. These comments will be mapped by Swagger UI to corresponding fields, displaying them in the documentation.

Similarly, model classes and their properties can be annotated with XML comments to provide Swagger Schema descriptions. For example:

public class Product
{
    /// <summary>
    /// The name of the product
    /// </summary>
    /// <example>Men's basketball shoes</example>
    public string Name { get; set; }

    /// <summary>
    /// Quantity left in stock
    /// </summary>
    /// <example>10</example>
    public int AvailableStock { get; set; }
}

Here, the <example> tag provides sample values, helping to demonstrate model usage in Swagger UI.

Supplementary Approach: Using SwaggerOperation Attributes

In addition to XML comments, the SwaggerOperation attribute from the Swashbuckle.AspNetCore.Annotations library can be used as a supplementary method. First, install the NuGet package, then enable annotations in Startup:

services.AddSwaggerGen(c =>
{
    c.EnableAnnotations();
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});

Next, use [SwaggerOperation(Summary = "Write your summary here")] on controller methods to add descriptions. This approach is more concise but may be less flexible than XML comments, especially for multilingual support or complex comment structures. Additionally, the [ApiExplorerSettings(IgnoreApi = true)] attribute can exclude public methods from appearing in Swagger UI to avoid potential conflicts.

Building and Verification

After completing the configuration, rebuild the project to update the XML comments file. Then, navigate to the Swagger JSON endpoint (typically /swagger/v1/swagger.json) to check if descriptions are correctly mapped. Finally, access the Swagger UI interface (e.g., https://localhost:5001/swagger) to verify that method descriptions are displayed as expected. For example, an API method for adding a pet might show as “POST: pet/ Description: Add a new pet to the store”.

During implementation, note the distinction between HTML tags and characters. For instance, in text content, if referring to the <br> tag as a described object rather than a line break instruction, it should be HTML-escaped to &lt;br&gt; to prevent it from being misinterpreted as HTML code, which could disrupt the DOM structure. This ensures content accuracy and readability.

In summary, by combining XML comments and Swagger configuration, rich method descriptions can be effectively added to Swagger UI, enhancing API documentation quality. Developers should choose the appropriate method based on project needs and follow best practices to ensure generated documentation is both detailed and maintainable.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.