Los*_*ost 11 c# restful-url swagger-ui swashbuckle asp.net-core-webapi
我使用Swagger作为我的API工具框架,到目前为止它运作良好.我刚看到这个页面https://petstore.swagger.io/
并看到每个方法如何描述.例如,
POST: pet/描述add a new Pet to the store.我想添加类似[Description("Description text")]应该做的事情,但事实并非如此.我怎样才能做到这一点?
Hel*_*eda 28
这在项目中有详细记载:https: //github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments
要使用人性化描述增强生成的文档,您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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; }
}
Run Code Online (Sandbox Code Playgroud)
5 - 重建项目以更新XML注释文件并导航到Swagger JSON端点.请注意描述如何映射到相应的Swagger字段.
注意:您还可以通过使用摘要标记注释API模型及其属性来提供Swagger架构描述.如果您有多个XML注释文件(例如,控制器和模型的单独库),您可以多次调用IncludeXmlComments方法,它们将全部合并到输出的Swagger JSON中.
按照说明仔细阅读,你应该得到如下内容:https:
//swashbucklenetcore.azurewebsites.net/swagger/
ala*_*tar 21
对于 ASP.Net Core 项目:
安装 nuget 包 Swashbuckle.AspNetCore.Annotations
将 SwaggerOperation 属性用于类似的方法 [SwaggerOperation(Summary = "Write your summary here")]
在启动方法 ConfigureServices 中启用注释,如下所示:
services.AddSwaggerGen(c =>
{
c.EnableAnnotations();
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
Run Code Online (Sandbox Code Playgroud)
要排除公共方法出现在 swagger ui 中,请使用属性[ApiExplorerSettings(IgnoreApi = true)]。这是有用的,因为这些方法可以出于某种原因打破招摇。
启动项目,转到 localhost:[端口号]/swagger 并享受。
Jon*_*rds 12
我们使用其他属性将所需的详细信息添加到 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()
{
...
}
Run Code Online (Sandbox Code Playgroud)
然后在你大摇大摆的配置中确保应用这些过滤器:
config.EnableSwagger("swagger",
c =>
{
c.OperationFilter<ApplySwaggerImplementationNotesFilterAttributes>();
c.OperationFilter<ApplySwaggerOperationSummaryFilterAttributes>();
Run Code Online (Sandbox Code Playgroud)
过滤器的代码:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
对于那些寻求公开自定义本地化控制器名称和操作描述而无需将 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()
};
}
}
Run Code Online (Sandbox Code Playgroud)
哪里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();
}
}
Run Code Online (Sandbox Code Playgroud)
适用于 Swashbuckle 5。
| 归档时间: |
|
| 查看次数: |
10179 次 |
| 最近记录: |