Swagger Failed to load API definition In ASP.NET Core API

In this article, we will learn how to resolve the ASP.NET Core API Swagger Failed to load API Definition issue.

You can refer to the following link for the related articles: 

What is the root cause of the API definition loading issue?

The default API controller route configuration is the cause of this issue. When we add the API controller in the ASP.NET Core API application, by default it has controller-specific routes, which means it can support only a single method for each of the HTTP verbs Post, PUT, Delete, GET, and Patch.

There may be a requirement when we need to create more than one method having the Http verbs Post, PUT, Delete, GET, and Patch in a single API controller, and if you create the method with the default route configuration in the API controller class without modifying the default route configuration, then you will get the exception "Failed to load API definition" while loading the swagger UI in the ASP.NET Core web API.

What is the Solution?

The solution is that you have to change the default route configuration at the controller level when you have created more than one method with the HTTP verbs "post," "put," and "get." Delete or Put in the single API controller class.

Consider the following example: I have created the ASP.NET Core API application, which has by default one Get method, GetWeatherForecast, which returns the WeatherForecast. Then I have added one more Get method named WeatherForecastByCity in the default API Controller class without modifying the default route.

 [ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [HttpGet(Name = "WeatherForecastByCity")]
    public IEnumerable<WeatherForecast> Get(string city)
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

When we have run the application, we will get the Swagger loading error,


Now change the default route at controller level which can support more than one method having the Http verbs Post, PUT, Delete, GET, and Patch in a single controller.

[Route("api/[controller]/[action])]

Also, remove the name of the method from the HTTP verb, which is defined using the Name attribute; just define the HTTP verb and proper method name.


Change from

   [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }


To 
 
   [HttpGet]
    public IEnumerable<WeatherForecast> GetWeatherForecast()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

Full Code







d[ApiController] [Route("api/[controller]/[action]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> GetWeatherForecast() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } [HttpGet] public IEnumerable<WeatherForecast> WeatherForecastByCity(string city) { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }

Now, run the application again after changing the default route, and you will see swagger loads without any issue.


Summary

I hope this article helps you fix the issue. "Swagger failed to load API definitions in the ASP.NET Core API." If you have any questions, then send them using the comment box.

Related Articles

How To Fix XML Comment Warning In ASP.NET Web API

While working with swagger documentation in an API we have to enabled the XML file to be generated for documentation from project setting and due to this reason all the pubic members in the project solution start giving the warnings "CS1591 Missing XML comment for publicly visible type or member" and if we specify the XML comment for those members then the same warning will be get disappeared but what for those members which are not a part of swagger documentation, If we ignore then their will be lots of warnings in the code which looks very uglier in the code, So in this article we will discuss how to resolve the "CS1591 missing XML comment for publicly visible type or member" warning.



CS1591 Missing XML Comment  Solution

Define XML Comment for All Public Members

As per me the best way is to define the XML comment for all public members whether its part of swagger UI document or not because of comments our method become more meaningful which help new developer to know about the method by comments instead of going through the code & understand the logic.




Another Advantage for defining the XML comment is, when developer implementing the any method in another class its show's the IntelliSense about the method which help developer to know what is the functionality of method without navigating to the method defined class.

Suppress Warning by Decorating each Public Member

Even though first approach has lots of advantages but you don't want to invest lots of time & increase the size of the project we can suppress the each public member by decorating with following line
#pragma warning disable CS1591


If you don't know the syntax then simply follow the visual studio suggestion by keeping the mouse on specific method or member






Suppress all Warnings at Project Level

The previous two approaches requires lots of time either defining the XML comment or  disabling the warning of each member in project.

To save the time & minimize the swagger comment related warnings we can disable these warning at project level itself with the just one line configuration, to achieve follows the following steps
Right click on api project solution & find the properties 


or just use Alt + Enter by putting control of project solution which opens the following window, find the options by following the below image & enter the 1591 in the suppress warnings text box & save it.



Now check any class file, you will not be see any warnings related to the swagger XML comment


Summary

Hope this article helped you to fix Warning CS1591 Missing XML comment for publicly visible type or member. If you like the contents the support by using the following way.

Related Articles

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode