Asp.Net 核心虚张声势设置操作 ID



如何在Core 2.1项目中设置 Asp.Net 摇摆operationId属性?根据这篇文章,我应该使用SwaggerOperationAttribute但我在Swashbuckle.AspNetCore库中找不到它。还有一个IOperationFilter

public interface IOperationFilter
{
void Apply(Operation operation, OperationFilterContext context);
}

而且我找不到任何用于招摇生成目的的实现。

还有其他 2 个选项,无需编写任何额外的代码或添加额外的依赖项,例如Swashbuckle.AspNetCore.Annotations

选项 1:基于约定 -SwaggerGen可以选择设置CustomOperationIds。因此,您可以简单地将其设置为使用如下所示ControllerName_HttpMethod

services.AddSwaggerGen(c =>
{
c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{e.HttpMethod}");
c.SwaggerDoc("v1", new Info { Title = "Test API", Version = "v1" });
});

这将按照约定将 operationId 添加到所有方法ControllerName_HttpMethod

选项 2:基于操作筛选器/属性 - 您可以配置每个操作方法(就像使用操作筛选器一样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

Name参数添加到[HttpGet]/[HttpPost]在最新版本中失败并出现异常,但在Route属性上放置Name参数似乎有效:

/// <summary>
/// Get all devices
/// </summary>
[Route("devices", Name = "GetAllDevices")]
[Authorize]
[HttpGet]
[Produces(typeof(Device[]))]
public async Task<IActionResult> GetAllDevices() { ...}

您还可以根据操作名称(即方法名称(生成操作 ID,我在生成 API 客户端时发现这很方便。

services.AddSwaggerGen(c =>
{
c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["action"]}");
c.SwaggerDoc("v1", new Info { Title = "Test API", Version = "v1" });
});

它非常简单

在配置服务方法中添加EnableAnnotations

{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Project HTTP API",
Version = "v1",
Description = "...."
});
options.EnableAnnotations();
});

并在控制器中使用

[SwaggerOperation(OperationId = "GET_API")]

你可以在Swagger Json中看到这一点

get": {
"tags": [
"API"
],
"summary": "....",
"operationId": "GET_API"
}

您可以使用 Swashbuckle.AspNetCore.Annotations NuGet 包在 swagger 上启用注释。(https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md#swashbuckleaspnetcoreannotations(

启用注释后,您可以通过使用 SwaggerOperationAttribute 修饰操作来丰富生成的操作元数据。

[HttpPost]
[SwaggerOperation(
Summary = "Creates a new product",
Description = "Requires admin privileges",
OperationId = "CreateProduct",
Tags = new[] { "Purchase", "Products" }
)]
public IActionResult Create([FromBody]Product product)

最后,我得出了这个解决方案:

public class SwaggerOperationNameFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
operation.OperationId = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<SwaggerOperationAttribute>()
.Select(a => a.OperationId)
.FirstOrDefault();
}
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class SwaggerOperationAttribute : Attribute
{
public SwaggerOperationAttribute(string operationId)
{
OperationId = operationId;
}
public string OperationId { get; }
}
// Startup.cs
services.AddSwaggerGen(c =>
{
...
c.OperationFilter<SwaggerOperationNameFilter>();
};
[HttpGet("{id:int}")]
[SwaggerOperation("GetById")]
public async Task<IActionResult> Get(int id)
{
...
}

但在我看来,我仍然重新发明了轮子。

添加此行 - 斯瓦格。CustomOperationIds(e => $"{e.RelativePath}"(; 在服务中。AddSwaggerGen 函数调用

最新更新