Integrate Swagger into ASP.NET Core

From Logic Wiki
Jump to: navigation, search

Step 1

PM > Install-Package Swashbuckle.AspNetCore

Step 2

Open Startup.cs file to add swagger service to middleware. Like:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info
        {
            Version = "v1",
            Title = "My API",
            Description = "My First ASP.NET Core Web API",
            TermsOfService = "None",
            Contact = new Contact() { Name = "Talking Dotnet", Email = "contact@talkingdotnet.com", Url = "www.talkingdotnet.com" }
        });
    });
}

Step 3

Enable the Swagger UI in Configure() method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc();
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
}

Optional Step 4

The one last thing to do is to change the application launch URL so that Swagger UI loads on launch.

To set Swagger UI as launch URL, right-click on Project -> select properties -> navigate to debug tab. On debug tab, change Launch Browser value to “swagger”. Set-Swagger-as-Launch.png

Extras

Show XML Comments

By default, swagger does not show XML comments. There is an option to display them with Swagger UI. First, we need to ensure that when the project is built, all the XML comments get saved in an XML file. Swagger will use this file to show XML comments on the Swagger UI.

To save XML comments in a file, right-click on the project -> properties and navigate to the build tab. On this tab, check “XML documentation file” option. XML-Setting.png By enabling this option, xml comments are saved in an XML file with the name [your assembly].xml. This file is located at bin\[Debug/Release]\netcoreapp2.0 folder. We need to pass this path Swashbuckle’s IncludeXMLComments method.

Add a method in Startup.cs to get the path of generated XML. This code to get the XML path will work in your local environment as well as in the production environment.

        private string GetXmlCommentsPath()
        {
            var app = System.AppContext.BaseDirectory;
            return System.IO.Path.Combine(app, "MDM.Api.xml");
        }

Next, add code to include XML comments in ConfigureService method. Like:

services.AddSwaggerGen(c =>
{
   c.IncludeXmlComments(GetXmlCommentsPath());
}

Next, add XML comments to our actions. Here is XML comment for Delete method.

// DELETE api/values/5
/// <summary>
/// Delete API Value
/// </summary>
/// <remarks>This API will delete the values.</remarks>
/// <param name="id"></param>
[HttpDelete("{id}")]
public void Delete(int id)
{
}

Showing Enum values as string

You can display the enum value as a string in the Swagger UI using DescribeAllEnumsAsStrings method. Like:

services.AddSwaggerGen(c =>
{
   c.IncludeXmlComments(GetXmlCommentsPath());
   c.DescribeAllEnumsAsStrings();
}

To see this in action, Let’s add an enum and modify Get method to accept enum type parameter.

public enum ValueType
{
    Number,
    Text
}

[HttpGet("{id}")]
public string Get(int id, ValueType type)
{
    return "value";
}

You should see the string value of enum are populated in the dropdown, instead of number (which is default).

Swagger-With-DescribeAllEnumsAsStrings.png

Different swagger documents for different API versions

If you have multiple versions of your WEB API, then you can use swagger to generate the different document based on the selected version. Like:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info
    {
        Version = "v1",
        Title = "My API",
        Description = "My First ASP.NET Core Web API",
        Contact = new Contact() { Name = "Talking Dotnet", Email = "contact@talkingdotnet.com", Url = "www.talkingdotnet.com" }
    });

    c.SwaggerDoc("v2", new Info
    {
        Version = "v2",
        Title = "New API",
        Description = "Sample Web API",
        Contact = new Contact() { Name = "Talking Dotnet", Email = "contact@talkingdotnet.com", Url = "www.talkingdotnet.com" }
    });
});

Read Support multiple versions of ASP.NET Core Web API to find out how to create/support multiple versions of the ASP.NET Core Web API. We also need to update the swagger UI to show multiple endpoints. They’ll be listed in the top right corner of the page, allowing users to toggle between the different documents.

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2");
}