我正在使用Swagger作为我的API工具框架,目前效果非常好。我刚刚发现了这个页面https://petstore.swagger.io/
并看到每个方法都有一个描述。例如,
POST: pet/
的描述为添加新宠物到商店中
。我认为添加类似于[Description("Description text")]
的东西就可以了,但它并没有起作用。我该如何实现这一点?
我正在使用Swagger作为我的API工具框架,目前效果非常好。我刚刚发现了这个页面https://petstore.swagger.io/
并看到每个方法都有一个描述。例如,
POST: pet/
的描述为添加新宠物到商店中
。我认为添加类似于[Description("Description text")]
的东西就可以了,但它并没有起作用。我该如何实现这一点?
为了增强生成的文档的易读性,您可以使用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/
MyApi.xml
只是一个示例,您可以将其命名为任何您想要的名称,只需要在整个解决方案中保持相同即可。 - Helder Sepulvedac.IncludeXmlComments(filePath);
XML 文档,以防您在另一个项目/库中定义了您的模型。 - Wouter Vanherck对于 ASP.Net Core 项目:
install nuget package Swashbuckle.AspNetCore.Annotations
Use SwaggerOperation attribute for a methods like [SwaggerOperation(Summary = "Write your summary here")]
Enable annotations in Startup method ConfigureServices like the following:
services.AddSwaggerGen(c =>
{
c.EnableAnnotations();
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
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 并享受。
我们使用附加属性来为 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文档或者发明其他属性的情况下,暴露自定义本地化控制器名称和操作描述的能力的人:
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();
}
}
一种解决方法是将以下内容添加到您的.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>
IncludeXmlComments
并在项目属性中启用输出,那么就能实现该功能。 - Kenneth K.