Migrate code 2.0 to 3.1 core code then swagger api versioning not working

Viewed 836

Cannot implicitly convert type
'System.Collections.Generic.Dictionary<string, Microsoft.OpenApi.Models.OpenApiPathItem>' to 'Microsoft.OpenApi.Models.OpenApiPaths'
An explicit conversion exists (are you missing a cast?)

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
            );
    }
}
2 Answers

It looks like OpenApiDocument.Path is not a dictionary So you can't use the swaggerDoc.Paths = swaggerDoc.Paths.ToDictionary() assignment

try with new OpenApiPath object and Add() method

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;

The type Microsoft.OpenApi.Models.OpenApiPaths inherits from the OpenApiExtensibleDictionary<OpenApiPathItem> and than inherits from the Dictionary<string, OpenApiPathItem>.

You can't use the swaggerDoc.Paths = swaggerDoc.Paths.ToDictionary(), but you can create new OpenApiPaths from the IDictionary<string, OpenApiPathItem>

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