使用c.CustomOperationIds时检查OperationId的唯一性吗?

时间:2020-06-09 09:00:21

标签: swashbuckle

目前,如果您使用以下内容

c.CustomOperationIds(apiDesc =>
{
    return apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null;
});

而且,由于程序员的错误,您有2个同名方法,不会警告您违反了OpenAPI规范

是否可以添加支票?

我在想要么

  • 在生成末尾,例如“ ID为{0}的2个操作”
  • 当swashbuckle调用CustomOperationId“ selector”时,具有访问已定义操作的钩子

感谢您的时间

P.S:使用Swashbuckle.AspNetCore.SwaggerGen 5.3.1

1 个答案:

答案 0 :(得分:0)

经过多次尝试,我发现了一种解决方法:使用操作过滤器,如果已经使用OperationId,它将引发异常

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;

namespace Service.Utils
{
    /// <summary>
    /// Guarantee that OperationId is not already used
    /// </summary>
    public class SwaggerUniqueOperationId : IOperationFilter
    {
        private readonly HashSet<string> ids = new HashSet<string>();

        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.OperationId != null)
            {
                if (ids.Contains(operation.OperationId))
                    throw new NotSupportedException($"There are 2 operations with same OperationId {operation.OperationId}");
                ids.Add(operation.OperationId);
            }
        }
    }
}

这根本不理想,因为错误消息非常模糊并且是运行时错误,但这比提供违反此唯一OperationId约束的OpenApi规范要好。

相关问题