繁体   English   中英

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

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

我使用 Swagger 作为我的 API 工具框架,到目前为止它运行良好。 我刚看到这个页面https://petstore.swagger.io/

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

POST: pet/是通过add a new Pet to the store描述的。 我认为添加类似[Description("Description text")]应该可以,但事实并非如此。 我怎样才能做到这一点?

这在项目中有详细记录: https : //github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments


包括来自 XML 注释的描述

为了使用人性化的描述增强生成的文档,您可以使用Xml 注释注释控制器操作和模型,并配置 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/

对于 ASP.Net Core 项目:

  1. 安装 nuget 包 Swashbuckle.AspNetCore.Annotations

  2. 将 SwaggerOperation 属性用于[SwaggerOperation(Summary = "Write your summary here")]

  3. 在启动方法 ConfigureServices 中启用注释,如下所示:

     services.AddSwaggerGen(c => { c.EnableAnnotations(); c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); });
  4. 要排除公共方法出现在 swagger ui 中,请使用属性[ApiExplorerSettings(IgnoreApi = true)] 这是有用的,因为这些方法可以出于某种原因打破招摇。

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

我们使用其他属性将所需的详细信息添加到 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()
    {
        ...
    }

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

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 文档发送给客户并发明另一堆属性的人:

    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。

一种解决方法是将其添加到您的.csproj文件中:

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

您可以对文档使用注释(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