2019年6月16日 星期日

[ASP.Net Core] Swagger - Integrate API Versioning


 ASP.NET Core   Web API   Versioning    Swagger 




Introduction


Swagger is a powerful open source framework that helps you design, build, document the RESTful APIs.
We are going to integrate API Versioning and Swagger to our Web API for documentation with multiple versions.



Related articles




Environment


.NET Core 2.2.104
Swashbuckle.AspNetCore 4.0.1
Visual Studio 2017 Community



Implement


Install Required Packages

·         Swashbuckle.AspNetCore





Enable XML document output

Set .csproj by Visual Studio:




Or edit .csproj as following,

<PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramewor>
 <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>


PS. In ASP.NET Core 3.X, it will be

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>obj\Debug\netcoreapp3.1\AspNetCore.IdentityServer4.Auth.xml</DocumentationFile>
  </PropertyGroup>




Enable Swagger

In Startup.cs, enable Swagger Generator for API's built.

public void ConfigureServices(IServiceCollection services)
{
   // Swagger
   services.AddSwaggerGen(c =>
   {
        c.SwaggerDoc(
           name: "MyAPI",
           info: new Swashbuckle.AspNetCore.Swagger.Info { Title = "MY APIs", Version = "v1" });
           c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
        });
   }
}


And enable the Route(JSON endpoint) and UI by:

n   UseSwagger:

Enable middleware to serve generated Swagger as a JSON endpoint.
Such as
http://localhost:<port>/swagger/v1/swagger.json.

n   UseSwaggerUI:

The Static File Middleware serves swagger-ui.
We have to specify the Swagger JSON endpoint for it.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   // Use Swagger
   app.UseSwagger(); // JSON endpoint
   app.UseSwaggerUI(c =>
   {
       c.SwaggerEndpoint(
             url:"/swagger/MyAPI/swagger.json",
             name:"My APIs V1.0");
   });

   app.UseMvc();
}


Notice that the <name> within JSON endpoint’s url:
http://localhost:<port>/swagger/<name>/swagger.json

MUST MATCH the value of SwaggerDoc’s name

c.SwaggerDoc(
           name: "MyAPI",
          // …
});



Result




API Document Versioning

However, we would to document the APIs with multiple versions.
Here we will modify the settings of Swagger middleware to integrate API Versioning for generating multi-version API document.


SwaggerConfig

First create a SwaggerConfig to inject it to the Swagger Generator.
The SwaggerConfig is used to get the API Versioning information from our APIs.

public class SwaggerConfig : IConfigureOptions<SwaggerGenOptions>
    {
        private readonly IApiVersionDescriptionProvider provider;

public SwaggerConfig(IApiVersionDescriptionProvider provider)
        {
            this.provider = provider;
        }

public void Configure(SwaggerGenOptions options)
        {
            foreach (var description in this.provider.ApiVersionDescriptions)
            {
                var info = new Swashbuckle.AspNetCore.Swagger.Info()
                {
                    Title = $"MY APIs {description.ApiVersion}",
                    Version = description.ApiVersion.ToString(),
                };

                options.SwaggerDoc(description.GroupName, info);
            }
        }
    }




Startup: ConfigureServices

Update/Add the services:

n   AddVersionedApiExplorer:
Adds an API explorer that is API version aware.

n   Inject customized SwaggerConfig to IConfigureOptions<SwaggerGenOptions>

n   Swagger Generator:
Use current assembly’s XML description

public void ConfigureServices(IServiceCollection services)
{
// Swagger
    services.AddVersionedApiExplorer(options => options.GroupNameFormat = "'v'VVV");
    services.AddTransient<IConfigureOptions<SwaggerGenOptions>, SwaggerConfig>();
    services.AddSwaggerGen(c =>
            {
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = System.IO.Path.Combine(System.AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
}



Startup: Configure



public void Configure(
            IApplicationBuilder app,
            IApiVersionDescriptionProvider provider)
 {
    // Use Swagger
    app.UseSwagger();
    app.UseSwaggerUI(options =>
       {
                    foreach (var description in provider.ApiVersionDescriptions)
                    {
                        options.SwaggerEndpoint(
                            $"/swagger/{description.GroupName}/swagger.json",
                            description.GroupName.ToUpperInvariant());
                    }
       });

     app.UseMvc();
 }

Here we make the Swagger UI supports multiple endpoints by IApiVersionDescriptionProvider’s GroupName information.


Demo

API Document Version 1.0:




API Document Version 2.0





Reference





沒有留言:

張貼留言