Skip to main content

Add Swagger to ASP.NET Core 2.0 Web API

Testing WEB APIs is a challenge, and it has a dependency on various third-party tools for proper and efficient testing. But swagger can make it easy. Swagger is an UI representation of your RESTful API. Swagger UI allows anyone — be it your development team or your end consumers — to visualize and interact with the API’s resources having none of the implementation logic in place. It’s automatically generated from your Swagger specification, with the visual documentation, making it easy for back-end implementation and client-side consumption. Earlier, I posted about adding swagger with ASP.NET Core but it no longer works with ASP.NET Core 2.0 due to new changes with ASP.NET Core 2.0. In this post, we’ll see how to add Swagger to ASP.NET Core 2.0 Web API.

Add Swagger to ASP.NET Core 2.0 Web API

Create a ASP.NET Core 2.0 WEB API project and install Swashbuckle.AspNetCore nuget package. Swashbuckle comprises three packages – a Swagger generator, middleware to expose the generated Swagger as JSON endpoints and middleware to expose a swagger-ui that’s powered by those endpoints. They can be installed together, via the Swashbuckle.AspNetCore meta-package. Like:

PM > Install-Package Swashbuckle.AspNetCore

The default template has ValuesContoller with API action method for all HTTP verbs. We’ll use the same for this post for showing Swagger UI.

Open Startup.cs file to add swagger service to middleware. Like:
And enable the Swagger UI in Configure() method.
This is all required to set up Swagger. 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”.

ASP.NET Core Set Swagger as Launch URL

Run the APP and you should see Swagger UI for ValuesContoller.

ASP.NET Core Set Swagger UI

Swagger uses different colors for each HTTP verb to differentiate API actions. Clicking on any method will give you details about accepted parameters, return type and allows you to test the method.

This is achieved with minimal configuration and without any customization. Swagger can be customized to include method’s XML comments, showing enum values as string values and generating different swagger document for different API version.

Show action’s XML Comments

We all are familiar with XML comments for documentation. 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.

ASP.NET Core Set Swagger UI XML Setting

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.ApplicationBasePath, “ASPNETCoreSwaggerDemo.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)
{
}

Now run the app, you should see XML comments.
ASP.NET Core Set Swagger UI XML Comments

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

There is also a method named DescribeStringEnumsInCamelCase to convert enum string values in camel case.

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:
Read this post 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.

Different swagger documents for different API versions

You can find the source code in the Github.

Conclusion

Swagger is a great tool to test your RESTFul APIs. Once integrated, it creates a simple UI to list down all your APIs actions and provide details about the request and response object for each API action. Integration with ASP.NET Core 2.0 is also straightforward and requires minimal efforts. Swagger also offers various customization to suit your needs.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

28 thoughts to “Add Swagger to ASP.NET Core 2.0 Web API”

  1. Hai This hepls me great !!!!
    In production release when i take production build then how to run swagger ?

  2. Any Idea why I get the following error after I added IncludeXmlComments()?

    > Fetch errorundefined /swagger/v1/swagger.json
    >
    > AmbiguousMatchException: Ambiguous match found. System.RuntimeType.GetMethodImplCommon(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers)

    I tripled check the .xml file path and it’s correct and the file is out there.

  3. How to enable Basic authentication with username and password pop-up asp.net core webapi.

  4. Hi, great article. So how do we put certain API on v1 and some on v2. I have tried using [ApiExplorerSettings(GroupName = “v2”)] attribute on my Action Method but its still appearing on both endpoints.

  5. For me is not working for an .NET Core 2 Angular Project, when I try the route /swagger it takes me back to the Home page…

      1. Thank you for the quick response, I understand that, but I have the following scenario, both: WebAPI and Angular Client App under the same project (ASP.NET Core) there are users that will access the UI built in Angular (no problem), but there are developers that will access the WebAPI, the developers asked for the WebAPI documentation, I enabled Swagger as described here, it generates the swagger.json file, but when I try to navigate to /swagger Angular router takes control and redirects me to the home page, I can not see the Swagger UI because Angular (or something else) is taking the route /swagger as an invalid route and redirecting me to home. Again Thank you

          1. I finally found the solution, on a Microsoft Doc post:

            I had to:

            – Acquire the contents of the dist folder from the Swagger UI GitHub repository. This folder contains the necessary assets for the Swagger UI page.
            – Create a wwwroot/swagger/ui folder, and copy into it the contents of the dist folder.

            Navigate to: http://localhost:/swagger/ui/index.html

            The index.html page needs to be changed to default the localhost/server name…

  6. Also there is no need to hardcode the name of the XML document. You can do this:

    private string GetXmlCommentsPath()
    {
    var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + “.XML”;
    return System.IO.Path.Combine(AppContext.BaseDirectory, commentsFileName);
    }

  7. Thanks for the article ,really useful.

    but I cannot find UseSwaggerUI method , i checked the swashbuckle package from nuget and it’s the latest v0.4.0.
    what am i missing here ?

    1. Dmitry,

      Swagger out of the box doesn’t have this kind of UI but it can be easily tweaked and customized. To tweak the look and feel, you can inject additional CSS stylesheets by adding them to your wwwroot folder and specifying the relative paths in the middleware options:

      app.UseSwaggerUI(c =>
      {

      c.InjectStylesheet(“/swagger-ui/custom.css”);
      }

      1. Thanks! Regarding this post. I would suggest to replace

        private string GetXmlCommentsPath()
        {
        var app = PlatformServices.Default.Application;
        return System.IO.Path.Combine(app.ApplicationBasePath, “ASPNETCoreSwaggerDemo.xml”);
        }

        with

        private string GetXmlCommentsPath()
        {
        var app = System.AppContext.BaseDirectory;
        return System.IO.Path.Combine(app.ApplicationBasePath, “ASPNETCoreSwaggerDemo.xml”);
        }

        as Platform Abstractions is obsolete and no longer used – https://github.com/aspnet/PlatformAbstractions

          1. Except that the value from ‘System.AppContext.BaseDirectory’ is a string and so it should be this:

            var appBasePath = System.AppContext.BaseDirectory;
            return System.IO.Path.Combine(appBasePath , “ASPNETCoreSwaggerDemo.xml”);

            Or simply:
            return System.IO.Path.Combine(System.AppContext.BaseDirectory, “ASPNETCoreSwaggerDemo.xml”);

Leave a Reply

Your email address will not be published. Required fields are marked *