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

时间:2018-10-18 22:27:54

标签: c# asp.net-core-webapi swagger-ui restful-url swashbuckle

我将Swagger用作我的API工具框架,到目前为止效果很好。我刚刚碰到了这个页面https://petstore.swagger.io/

,并查看了每种方法的描述。例如,

POST: pet/add a new Pet to the store描述。我认为添加[Description("Description text")]之类的内容应该可以,但事实并非如此。我该如何实现?

6 个答案:

答案 0 :(得分:16)

这在项目中有详细记录: 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 Comments文件并导航到Swagger JSON端点。请注意如何将描述映射到相应的Swagger字段。

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


请仔细按照说明进行操作,以获取类似于以下内容的内容:
https://swashbucklenetcore.azurewebsites.net/swagger/

答案 1 :(得分:11)

对于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:[port number] / swagger享受。

答案 2 :(得分:2)

对于那些希望能够公开自定义 localized 控制器名称和操作说明而又不向客户发送XML文档和发明又一堆属性的人:

mydata <- structure(list(state = c("IN", "KY", "OH", "TX"), log = c("log_PRICE", 
"log_PRICE", "log_PRICE", "log_PRICE"), estimate = c(-1.105977, 
-1.0459502, -0.9076732, -0.2252409), se = c(0.05943414, 0.0341025, 
0.01259117, 0.01053847), statistic = c(-18.60845, -30.67078, 
-72.08806, -21.37321), pvalue = c(7.186435e-72, 2.739798e-196, 
0, 4.11749e-101)), class = "data.frame", row.names = c(NA, -4L
))

其中 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

适用于Swashbuckle 5。

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

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