CoO*_*oOl 3 swagger swashbuckle asp.net-core
我正在使用aspnet core 2.2创建Restful API。我有一个标准设置,其中每个模型都有一个带有GET和POST动作的自己的控制器。我使用的Swashbuckle.AspNetCoreNuGet包,并使用该文章从微软的文档。
现在,当我查看生成的swagger文件时,它具有多个GET和POST operationIds。如何在不使用的情况下配置自定义operationIds Swashbuckle.AspNetCore.Annotations?
这是我的Action方法的样子:
[HttpPost]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Response>> PostAsync([FromBody]Request request)
{
Response result = await _context.PostAsync(request);
return Ok(result);
}
Run Code Online (Sandbox Code Playgroud)
我有多个控制器,它们都遵循相同的模式。
我的启动类如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
...
}
Run Code Online (Sandbox Code Playgroud)
我已经看过这种解决方案,但不想走那条路。
在花了几个小时试图找到最佳解决方案之后,我发现了两种方法:
选项1:基于约定- SwaggerGen有设置选项CustomOperationIds。因此,您可以将其设置为ControllerName_HttpMethod如下所示:
services.AddSwaggerGen(c =>
{
c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{e.HttpMethod}");
c.SwaggerDoc("v1", new Info { Title = "ID&V API", Version = "v1" });
});
Run Code Online (Sandbox Code Playgroud)
遵循ControllerName_HttpMethod约定,这会将operationIds添加到您的所有方法中。
选项2:基于ActionFilter / Attribute的-您可以配置每个Action方法(就像您SwaggerOperation通过简单地向NameHTTP谓词操作过滤器添加属性一样使用操作过滤器一样:
[HttpPost(Name="Post_Person")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Response>> PostAsync([FromBody]Request request)
{
Response result = await _context.PostAsync(request);
return Ok(result);
}
Run Code Online (Sandbox Code Playgroud)
这完全一样,[SwaggerOperation(OperationId = "Post_Person")]但不需要EnableAnnotations
Swashbuckle.AspNetCore文档可以在这里找到
| 归档时间: |
|
| 查看次数: |
841 次 |
| 最近记录: |