gpt4 book ai didi

asp.net-core - AspNetCore 自定义/显式 Swagger OperationId

转载 作者:行者123 更新时间:2023-12-02 00:46:18 26 4
gpt4 key购买 nike

我正在使用 aspnet core 2.2 创建 Restful API。我有一个标准设置,其中每个模型都有自己的 Controller ,带有 GETPOST 操作。我正在使用 Swashbuckle.AspNetCore NUGET 包并使用 this来自 Microsoft 文档的文章。

现在,当我查看生成的 swagger 文件时,它有多个 GET 和 POST 操作 ID。如何在不使用 Swashbuckle.AspNetCore.Annotations 的情况下配置自定义操作Id?

这是我的操作方法:

[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);
}

我有多个 Controller ,它们都遵循相同的模式。

我的启动类如下所示:

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");
});

...
}

我已经看过this解决方案,但不想走那条路。

最佳答案

花了几个小时试图找到最佳解决方案后,我发现了两种方法:

选项 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" });
});

这将按照 ControllerName_HttpMethod 约定将 operationId 添加到您的所有方法中。

选项 2:基于 ActionFilter/Attribute - 您可以配置每个 Action 方法(就像使用 SwaggerOperation 操作过滤器一样,只需添加 Name 属性添加到您的 HTTP 动词操作过滤器,如下所示:

[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);
}

这与[SwaggerOperation(OperationId = "Post_Person")]完全相同,但不需要EnableAnnotations

Swashbuckle.AspNetCore 文档可以找到 here

关于asp.net-core - AspNetCore 自定义/显式 Swagger OperationId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54293378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com