如何在WebAPI应用程序中的Swagger UI中添加方法描述

74

我正在使用Swagger作为我的API工具框架,目前效果非常好。我刚刚发现了这个页面https://petstore.swagger.io/

并看到每个方法都有一个描述。例如,

POST: pet/的描述为添加新宠物到商店中。我认为添加类似于[Description("Description text")]的东西就可以了,但它并没有起作用。我该如何实现这一点?


6个回答

152
这在项目中有明确的文档说明:https://github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments

包含XML注释中的描述信息

为了增强生成的文档的易读性,您可以使用Xml Comments对控制器操作和模型进行注释,并配置Swashbuckle将这些注释合并到输出的Swagger JSON中:

1 - 打开项目的属性对话框,点击“生成”选项卡,并确保“XML文档文件”已选中。这将在构建时生成一个包含所有XML注释的文件。

此时,任何未用XML注释注释的类或方法都会触发构建警告。为了抑制这种情况,请在属性对话框中的“抑制警告”字段中输入警告代码“1591”。

2 - 配置Swashbuckle将文件中的XML注释合并到生成的Swagger JSON中:

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

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

3 - 用摘要、备注和响应标签注释您的操作:

/// <summary>
/// Retrieves a specific product by unique id
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Product created</response>
/// <response code="400">Product has missing/invalid values</response>
/// <response code="500">Oops! Can't create your product right now</response>
[HttpGet("{id}")]
[ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(500)]
public Product GetById(int id)

4 - 您还可以使用摘要和示例标签注释类型:

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

5 - 重新构建项目以更新XML注释文件并导航到Swagger JSON端点。请注意,描述将映射到相应的Swagger字段。

注意:您还可以通过使用摘要标记注释API模型及其属性来提供Swagger模式描述。如果您有多个XML注释文件(例如,控制器和模型的单独库),您可以多次调用IncludeXmlComments方法,它们将合并到输出的Swagger JSON中。


按照说明仔细操作后,您应该得到类似于:
https://swashbucklenetcore.azurewebsites.net/swagger/


@WorkBee,你真的不需要看到XML应该是什么样子的...这是由VisualStudio根据您的注释自动生成的,而Swashbuckle知道如何读取它...另外,名称MyApi.xml只是一个示例,您可以将其命名为任何您想要的名称,只需要在整个解决方案中保持相同即可。 - Helder Sepulveda
1
这是一个非常好的关于如何在Swagger中使用描述的说明,正如@HelderSepulveda所说,你在步骤1中进行的设置是生成XML文件的设置。你也可以在那里放置任何名称,但请确保在步骤2中使用相同的名称(如MyApi.xml所描述)。 - Martin Florin
这正是我整个下午一直在寻找的东西。为了在Swagger UI查询字符串的描述中显示我的XML注释,我检查了项目属性中的“XML文档文件”设置,并添加了“IncludeXmlComments(filepath)”。谢谢! - jet_choong
不要忘记通过属性构建并引用 c.IncludeXmlComments(filePath); XML 文档,以防您在另一个项目/库中定义了您的模型。 - Wouter Vanherck
2
在 .net core 中,设置名称为“Documentation File”。谢谢,非常有帮助。 - SamBerk
显示剩余2条评论

54

对于 ASP.Net Core 项目:

  1. install nuget package Swashbuckle.AspNetCore.Annotations

  2. Use SwaggerOperation attribute for a methods like [SwaggerOperation(Summary = "Write your summary here")]

  3. Enable annotations in Startup method ConfigureServices like the following:

    services.AddSwaggerGen(c =>
    {
        c.EnableAnnotations();
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
    
  4. To exclude public method from appearing in swagger ui use attribute [ApiExplorerSettings(IgnoreApi = true)]. It is useful cause these methods can break swagger for some reason.

启动项目,打开 localhost:[端口号] / swagger 并享受。


谢谢你的解决方案。 同时,我的代码与两个使用有冲突,它可以这样工作: [Swashbuckle.AspNetCore.Annotations.SwaggerOperation(Summary = "")] - hossein andarkhora
1
我认为这是正确的答案,这就是 OP 希望能够直接使用的功能。这只是与原始 Swashbuckle 相同开发者的另一个附加包。 - mathiash

23

我们使用附加属性来为 Swagger 文档添加必要的详细信息:

    [SwaggerOperationSummary("Add a new Pet to the store")]
    [SwaggerImplementationNotes("Adds a new pet using the properties supplied, returns a GUID reference for the pet created.")]
    [Route("pets")]
    [HttpPost]
    public async Task<IHttpActionResult> Post()
    {
        ...
    }

然后在你的swagger配置中确保应用这些过滤器:

config.EnableSwagger("swagger",
           c =>
           {
               c.OperationFilter<ApplySwaggerImplementationNotesFilterAttributes>();
               c.OperationFilter<ApplySwaggerOperationSummaryFilterAttributes>();

筛选器的代码:

public class ApplySwaggerImplementationNotesFilterAttributes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var attr = apiDescription.GetControllerAndActionAttributes<SwaggerImplementationNotesAttribute>().FirstOrDefault();
        if (attr != null)
        {
            operation.description = attr.ImplementationNotes;
        }
    }
}

public class ApplySwaggerOperationSummaryFilterAttributes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var attr = apiDescription.GetControllerAndActionAttributes<SwaggerOperationSummaryAttribute>().FirstOrDefault();
        if (attr != null)
        {
            operation.summary = attr.OperationSummary;
        }
    }
}

我在想,为什么这不是一个被接受的答案。XML文档不是一种好的方式。首先,XML文档用.NET术语描述了所有内容。想象一下,你的REST使用ABAP开发人员。第二个问题是,分发XML文档的原因是什么?第三个问题是,如果我想要本地化的文档呢? - Dennis
3
没有人直接阅读XML文档本身,这对ABAP开发者有什么关系呢?这不被接受是因为其他问题用更少的代码以本地方式回答了这个问题。 - djsoteric
我在以下链接中找到了使用 .net core 实现此功能的方法:https://newbedev.com/how-to-add-method-description-in-swagger-ui-in-webapi-application - Aniyan Kolathur
什么是SwaggerImplementationNotesAttribute? - toha

6

对于那些寻求能够在不向客户端发送XML文档或者发明其他属性的情况下,暴露自定义本地化控制器名称和操作描述的能力的人:

    public static class SwaggerMiddlewareExtensions
    {
        private static readonly string[] DefaultSwaggerTags = new[]
        {
            Resources.SwaggerMiddlewareExtensions_DefaultSwaggerTag
        };

        public static void ConfigureSwagger(this IServiceCollection services)
        {
            services
                .AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                    {
                        Title = "My API",
                        Version = "v 1.0"
                    });

                    // your custom config

                    // this will group actions by localized name set in controller's DisplayAttribute
                    options.TagActionsBy(GetSwaggerTags);
                    
                    // this will add localized description to actions set in action's DisplayAttribute
                    options.OperationFilter<DisplayOperationFilter>();
                });
        }

        private static string[] GetSwaggerTags(ApiDescription description)
        {
            var actionDescriptor = description.ActionDescriptor as ControllerActionDescriptor;

            if (actionDescriptor == null)
            {
                return DefaultSwaggerTags;
            }

            var displayAttributes = actionDescriptor.ControllerTypeInfo.GetCustomAttributes(typeof(DisplayAttribute), false);

            if (displayAttributes == null || displayAttributes.Length == 0)
            {
                return new[]
                {
                    actionDescriptor.ControllerName
                };
            }

            var displayAttribute = (DisplayAttribute)displayAttributes[0];

            return new[]
            {
                displayAttribute.GetName()
            };
        }
    }

其中DisplayOperationFilter是:

    internal class DisplayOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var actionDescriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;

            if (actionDescriptor == null)
            {
                return;
            }

            var displayAttributes = actionDescriptor.MethodInfo.GetCustomAttributes(typeof(DisplayAttribute), false);

            if (displayAttributes == null || displayAttributes.Length == 0)
            {
                return;
            }

            var displayAttribute = (DisplayAttribute)displayAttributes[0];

            operation.Description = displayAttribute.GetDescription();
        }
    }

适用于 Swashbuckle 5。

2

一种解决方法是将以下内容添加到您的.csproj文件中:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DocumentationFile>bin\Debug\netcoreapp1.1\FileXMLName.xml</DocumentationFile>
</PropertyGroup>

4
通过 Visual Studio 中的项目属性进行此操作的结果是:右键单击(您的项目)> 属性 > 构建 > 输出部分 > 选中“XML 文档文件”。 - fix

1

您可以使用注释进行文档编写(3个斜杠而不是标准的2个),例如:

/// <summary>
/// This is method summary I want displayed
/// </summary>
/// <param name="guid">guid as parameter</param>
/// <param name="page_number">Page number - defaults to 0</param>
/// <returns>List of objects returned</returns>

7
如果您在Swagger配置中指定了IncludeXmlComments并在项目属性中启用输出,那么就能实现该功能。 - Kenneth K.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接