Question

[Solved] Swagger not loading – Failed to load API definition: Fetch error undefined

Trying to setup swagger in conjunction with a web application hosted on IIS express. API is built using ASP Net Core. I have followed the instructions prescribed on the relevant microsoft help page regarding Swashbuckle and ASP.NET Core.

Thus far I have got the swagger page to load up and can see that the SwaggerDoc that I have defined is loading, however no API’s are present. Currently am getting the following error:

“Fetch error undefined ./swagger/v1/swagger.json”

public class Startup
{

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // services.AddDbContext<TodoContext>(opt =>
        // opt.UseInMemoryDatabase("TodoList"));
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "API WSVAP (WebSmartView)", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1");
            c.RoutePrefix = string.Empty;
        });

        app.UseMvc();
    }
}

Solution #1:

So after a lot of troubleshooting it came down to basically two things, but I feel that in general this could be helpful to someone else in the future so I’m posting an answer.

First- if ever your stuck with the aforementioned error the best way to actually see whats going on is by adding the following line to your Configure() method

app.UseDeveloperExceptionPage();

Now if you navigate to the ‘swagger/v1/swagger.json’ page you should see some more information which will point you in useful direction.

Second- now for me the error was something along the lines of

‘Multiple operations with path ‘some_path’ and method ‘GET’ ‘

However these API were located inside of dependency libraries so I was unable to apply a solution at the point of definition. As a workaround I found that adding the following line to your ConfigureServices() method resolved the issue

services.AddSwaggerGen(c =>
{
     c.SwaggerDoc("v1", new Info { Title = "API WSVAP (WebSmartView)", Version = "v1" });
     c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); //This line
});

Finally- After all that I was able to generate a JSON file but still I wasn’t able to pull up the UI. In order to get this working I had to alter the end point in Configure()

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

I’m not sure why this was necessary, although it may be worth noting the web application’s virtual directory is hosted on IIS which might be having an effect.

Hope this helps someone in the future.

Respondent: Jeremy S.

Solution #2:

I’ve been working with .Net Core 3.1 and I spent some time to find out and understanding what was going on.

The issue can arise from many different reasons:

enter image description here

  1. Swagger configuration errors

  2. Classes with the same name but in different namespaces

  3. Public methods without the rest attribute (Get, Post, etc.)

First, take a look the link below just to check if your setup is ok:

Add Swagger(OpenAPI) API Documentation in ASP.NET Core 3.1

Then,

A good tip to find out the problem is to run the application without to use IISExpress and check the console log. Any error found to generate the documentation will be displayed there.

In my case, the problems was that I had a public method (that should be private) without any rest attribute:

enter image description here

After change the method from public to private I solve the issue.

Respondent: Julio Schurt

Solution #3:

I was able to find the error by opening the network tab and looking at the response for swagger.json

enter image description here

Respondent: YOrnstei

Solution #4:

Simply navigate to https://localhost:{PortNo}/swagger/v1/swagger.json and get much more details about the error message.

Respondent: Mohammed Osman

Solution #5:

I had similar issue, I solved it using the Route attribute on the offending controller method:

[HttpGet, Route("Throw")]
public ActionResult<string> Throw()
{
    _logger.LogInformation("I think I am going to throw up");
    throw new NotSupportedException("For testing unhandled exception logging.");
}

I felt that ResolveConflictingActions may potentially sweep a real issue under the rug.

Respondent: Arthur

Solution #6:

I had two issues that caused the same error.

  1. I have two classes with the same name under two different namespaces. Swagger could not reconcile this when generating the swagger doc. To fix it I added the line options.CustomSchemaIds(x => x.FullName);
    See explanation here

  2. I had a method without an [HttpGet] annotation. Swagger needs the HTTP endpoints to be explicitly defined.

I found both issues by inspecting the Output in visual studio after the API loaded.

Respondent: LazyDog

Solution #7:

I just spent two hours on this issue, but my cause was entirely different, it had NOTHING to do with routes or annotations. I had 2 classes with the same name (but different namespaces): MyProject.Common.ClassName and MyProject.Api.ClassName. Swagger/swashbuckle couldn’t tell the difference between the two, so I got that useless error.

Those 2 hours were spent trial-and-error commenting out controllers and endpoints, to finally find 3 endpoints offending endpoints. All 3 endpoints had different routes, different (or no) custom authorization, and different method names. It turned out that all 3 endpoints either accepted a parameter, or returned an object, that contained the API version of my class. Nowhere was the Common version used. Swagger couldn’t tell them apart, and puked all over itself.

Why oh why can’t Swagger or Swashbuckle provide actual error messages? Would have saved me a couple of hours…

Respondent: emery.noel

Solution #8:

I’ve come across the same error before, after struggling to find the reason, I discovered that one of my API in one of my controllers have no HTTP verb as an attribute, So I fixed it by putting [HttpGet] on my API.
So here is my advice, check your API controllers, maybe you forget the same thing as me!

Take a look at my code, I realized that I should change this :

   public async Task<Product> ProductDetail(int id)
    {
        return await _productQueries.GetProductDetail(id);
    } 

to this:

        [Route("ProductDetail")]
        [HttpPost]
        public async Task<Product> ProductDetail(int id)
        {
            return await _productQueries.GetProductDetail(id);
        } 
Respondent: Hamid

Solution #9:

also I had similar problem in .NET 5.0, I solved below way:

enter image description here

I added this line as attribute over controller:

[Consumes("application/json")]
Respondent: Yusif Karimov

Solution #10:

In my case, there were 2 methods in the Controller class, which had the same annotations, and URL. (Our team was using Entity Framework, ASP.NET and Swagger.)

    [HttpGet("GetMyGreatData/{patientId}")]
    [ValidatePatient]
    public async Task<ActionResult<ServiceResponse<IEnumerable<MyGreatModel>>>> GetMyGreatData(
    [FromRoute] int patientId, int offset = 0, int limit = 0)
    {
        //method details...
    }


    [HttpGet("GetMyGreatData/{patientId}")]
    [ValidatePatient]
    public async Task<ActionResult<ServiceResponse<IEnumerable<MyGreatModel>>>> GetMyGreatData( 
    [FromRoute] int patientId, 
    [FromQuery] DateTimeOffset? startdate = null,
    [FromQuery] DateTimeOffset? endDate = null,
    int offset = 0,
    int limit = 0)
    {
        //method details...
    }

deleting one method solved the issue for me.

Respondent: Onat Korucu

Solution #11:

I was having the same issue, the base controller was not decorated with Http and removing that has made it work.

Respondent: Naod Agere

Solution #12:

This error can happen when you deploy an App Service to Azure. I’ve redeployed the App Service to Azure and the error disappeared.

Respondent: Martin Staufcik

Solution #13:

When this happened to me, I tracked it down to URL path param having an underscore which it’s compatible with the asp generator

Changing this:

/block-content/{machine_name}:

To this

/block-content/{machineName}:

Solved it for me

Respondent: nigelheap

Solution #14:

I just forgot to add HTTP attributes in my controller as soon as I add HTTP attribute it works like a charm for me.
enter image description here

Source : https://www.benday.com/2020/12/16/webapi-core-swagger-failed-to-load-api-definition-error/

Respondent: Nafees Sardar

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy