简体   繁体   English

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

[英]How to add method description in Swagger UI in WebAPI Application

I am using Swagger as my API tooling framework and it is working out great so far.我使用 Swagger 作为我的 API 工具框架,到目前为止它运行良好。 I just came across this page https://petstore.swagger.io/我刚看到这个页面https://petstore.swagger.io/

and saw how each method has a description.并看到每个方法如何有描述。 For example,例如,

POST: pet/ is described by add a new Pet to the store . POST: pet/是通过add a new Pet to the store描述的。 I thought adding something like [Description("Description text")] should do it but it just does not.我认为添加类似[Description("Description text")]应该可以,但事实并非如此。 How can I achieve this?我怎样才能做到这一点?

This is well documented in the project: https://github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments这在项目中有详细记录: https : //github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments


Include Descriptions from XML Comments包括来自 XML 注释的描述

To enhance the generated docs with human-friendly descriptions, you can annotate controller actions and models withXml Comments and configure Swashbuckle to incorporate those comments into the outputted Swagger JSON:为了使用人性化的描述增强生成的文档,您可以使用Xml 注释注释控制器操作和模型,并配置 Swashbuckle 以将这些注释合并到输出的 Swagger JSON 中:

1 - Open the Properties dialog for your project, click the "Build" tab and ensure that "XML documentation file" is checked. 1 - 打开项目的属性对话框,单击“构建”选项卡并确保选中“XML 文档文件”。 This will produce a file containing all XML comments at build-time.这将在构建时生成一个包含所有 XML 注释的文件。

At this point, any classes or methods that are NOT annotated with XML comments will trigger a build warning.此时,任何没有用 XML 注释注释的类或方法都会触发构建警告。 To suppress this, enter the warning code "1591" into the "Suppress warnings" field in the properties dialog.要抑制这种情况,请在属性对话框的“抑制警告”字段中输入警告代码“1591”。

2 - Configure Swashbuckle to incorporate the XML comments on file into the generated Swagger JSON: 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 - Annotate your actions with summary, remarks and response tags: 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 - You can also annotate types with summary and example tags: 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 - Rebuild your project to update the XML Comments file and navigate to the Swagger JSON endpoint. 5 - 重建您的项目以更新 XML 注释文件并导航到 Swagger JSON 端点。 Note how the descriptions are mapped onto corresponding Swagger fields.请注意描述如何映射到相应的 Swagger 字段。

NOTE: You can also provide Swagger Schema descriptions by annotating your API models and their properties with summary tags.注意:您还可以通过使用摘要标签注释 API 模型及其属性来提供 Swagger 架构描述。 If you have multiple XML comments files (eg separate libraries for controllers and models), you can invoke the IncludeXmlComments method multiple times and they will all be merged into the outputted Swagger JSON.如果您有多个 XML 注释文件(例如,控制器和模型的单独库),您可以多次调用 IncludeXmlComments 方法,它们都将合并到输出的 Swagger JSON 中。


Following the instructions carefully you should get something that looks like:仔细按照说明操作,您应该得到如下所示的内容:
https://swashbucklenetcore.azurewebsites.net/swagger/ https://swashbucklenetcore.azurewebsites.net/swagger/

For ASP.Net Core projects:对于 ASP.Net Core 项目:

  1. install nuget package Swashbuckle.AspNetCore.Annotations安装 nuget 包 Swashbuckle.AspNetCore.Annotations

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

  3. Enable annotations in Startup method ConfigureServices like the following:在启动方法 ConfigureServices 中启用注释,如下所示:

     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)] .要排除公共方法出现在 swagger ui 中,请使用属性[ApiExplorerSettings(IgnoreApi = true)] It is useful cause these methods can break swagger for some reason.这是有用的,因为这些方法可以出于某种原因打破招摇。

Launch project, go to localhost:[port number]/swagger and enjoy.启动项目,转到 localhost:[端口号]/swagger 并享受。

We use additional attributes to add required detail to the swagger documentation:我们使用其他属性将所需的详细信息添加到 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()
    {
        ...
    }

And then in you swagger config make sure to apply these filters:然后在你大摇大摆的配置中确保应用这些过滤器:

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

The code for the filters:过滤器的代码:

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

For those who looks for ability to expose custom localized controller names and action descriptions without shipping XML documents to customer and inventing yet another bunch of attrubutes:对于那些寻求公开自定义本地化控制器名称和操作描述而不将 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()
            };
        }
    }

where DisplayOperationFilter is:其中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();
        }
    }

Applicable for Swashbuckle 5.适用于 Swashbuckle 5。

A workaround is to add this to your .csproj file:一种解决方法是将其添加到您的.csproj文件中:

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

You can use comment for documentation (3 slashes instead of standard 2) like:您可以对文档使用注释(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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM