首页 > 解决方案 > 使用 c.CustomOperationIds 时检查 OperationId 的唯一性?

问题描述

目前,如果您使用以下

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

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

有没有办法添加支票?

我想要么

谢谢你的时间

PS:使用 Swashbuckle.AspNetCore.SwaggerGen 5.3.1

标签: swashbuckle

解决方案


经过多次尝试,我找到了一种解决方法:使用一个操作过滤器,如果 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 规范要好...


推荐阅读