DEV Community

Discussion on: Versioning ASP.Net Core APIs with Swashbuckle - Making Space Potatoes V-x.x.x

Collapse
 
codeswayslay profile image
Akin Agbaje • Edited

This is a great tutorial. Thanks.

I did get stuck at some point.

With .NET Core 3.1, Swashbuckle has changed a number of things. The "Apply" method in the class that implements the IDocumentFilter should be updated to this:

public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            var toReplaceWith = new OpenApiPaths();

            foreach (var (key, value) in swaggerDoc.Paths)
            {
                toReplaceWith.Add(key.Replace("v{version}", swaggerDoc.Info.Version, StringComparison.InvariantCulture), value);
            }

            swaggerDoc.Paths = toReplaceWith;
        }
Enter fullscreen mode Exit fullscreen mode

Also, the predicate that ensures endpoints are displayed in their appropriate swagger doc should be updated:

setup.DocInclusionPredicate((version, desc) => 
                {
                    if (!desc.TryGetMethodInfo(out MethodInfo methodInfo))
                        return false;

                    var versions = methodInfo.DeclaringType
                    .GetCustomAttributes(true)
                    .OfType<ApiVersionAttribute>()
                    .SelectMany(attr => attr.Versions);

                    var maps = methodInfo
                    .GetCustomAttributes(true)
                    .OfType<MapToApiVersionAttribute>()
                    .SelectMany(attr => attr.Versions)
                    .ToArray();

                    return versions.Any(v => $"v{v.ToString()}" == version)
                    && (!maps.Any() || maps.Any(v => $"v{v.ToString()}" == version));
                });
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mustafasalahuldin profile image
Mustafa Salaheldin

Saved my day.

Collapse
 
gabehunt profile image
Gabe Hunt

Thank you ... this is exactly what I needed!