将代码2.0迁移到3.1核心代码,然后招摇api版本控制不起作用



无法隐式转换类型
'System.Collections.Generic.Dictionary<一串Microsoft.OpenApi.Models.OpenApiPathItem>'到'Microsoft.OpenApi.Models.OpenApiPaths'
存在显式转换(是否缺少强制转换?(

public class ReplaceVersionWithExactValueInPath : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.Paths = swaggerDoc.Paths
            .ToDictionary(
                path => path.Key.Replace("v{version}", swaggerDoc.Info.Version),
                path => path.Value
            );
    }
}

看起来OpenApiDocument.Path不是字典所以你不能使用swaggerDoc.Paths = swaggerDoc.Paths.ToDictionary()分配

尝试新的OpenApiPath对象和Add()方法

var oap = new OpenApiPaths();
foreach (var p in swaggerDoc.Paths)
    oap.Add(p.Key.Replace("v{version}", swaggerDoc.Info.Version),
        p.Value);
swaggerDoc.Paths = oap;

类型Microsoft.OpenApi.Models.OpenApiPathsOpenApiExtensibleDictionary<OpenApiPathItem>继承,而不是从Dictionary<string, OpenApiPathItem>继承。

您不能使用swaggerDoc.Paths = swaggerDoc.Paths.ToDictionary(),但可以从IDictionary<string, OpenApiPathItem> 创建新的OpenApiPaths

var paths = new OpenApiPaths(swaggerDoc
              .Paths
              .ToDictionary(
                  path => path.Key.Replace("v{version}", swaggerDoc.Info.Version),
                  path => path.Value)
            );
swaggerDoc.Paths = paths;

相关内容

最新更新