Swagger not loading - Failed to load API definition: Fetch error undefined
Asked Answered
M

33

109

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();
    }
}
Mini answered 2/7, 2019 at 20:24 Comment(7)
Can you explain what's going on in the Startup where you're assigning an interface to the Configuration class?Agueda
Use c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");Homovec
jPhizzle - this was left over from previous troubleshooting attempts. I have updated the code. ApologiesMini
Akash KC - I had tried this originally unfortunately no change.Mini
What's the error message on the Console tab in the browser dev tools?Godmother
'Failed to load resource: the server responded with a status of 404 () ... swagger/v1/swagger.json:1 'Mini
@Godmother for whatever reason it didn't occur to me to check DevTools... Becuase of your comment I found out that Swagger doesn't like that I have a conflict with two DTOs having the same name. They're in different namespaces but apparently that's not good enough. Anyway, thanks for the idea of where to check!Brownell
M
154

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.

NOTE: Navigating to swagger/v1/swagger.json will give you more details, for me it was causing issue due to undecorated action. This information is mentioned in comment by @MarkD

Mini answered 9/7, 2019 at 19:5 Comment(6)
navigating directly to the swagger/v1/swagger.json solved this. An undecorated action.Solfatara
The navigation to swagger/v1/swagger.json also gave me the solution to my problem - action needed an explicit [HttpGet] attributeBrufsky
Navigate to your application's swagger.json in your browser has shown the error clearly. localhost:808/swagger/v1/swagger.jsonTabethatabib
adding this line ResolveConflictingActions resolved my issue.Cranio
I also had change that same endpoint path to "./v1/swagger..." to get it working on the web server. Very strange requirement. The new path works fine in local debug and on the server. Seems like it would be the default from the project template.Strake
I had a similar case to @Mog0, because of copy-paste from another method, I applied HttpGet attribute for POST method (oversight), so I had two HttpGet methods with the same routing.Frosty
D
54

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.

Dwell answered 1/10, 2020 at 22:8 Comment(6)
For me it was number three. "Public methods without the rest attribute" You help me very muth. Thanks!Diffractive
Another reason, which I just encountered, is when the name of the attribute [HttpPost("NAME_HERE") isn't the same as the action name.Landonlandor
For me, it was 'Classes with the same name but in different namespaces'. I have a .Net Core Api and had a 'User' class in two different namespaces. Renaming the second corrected the issueVespers
For me, it is number 3. Thanks.Rightward
for me it was number 2. I ended up having to smurf name things a little which was a little sad but understandable.Adolfoadolph
for me, it was number 3. thanksRoseline
A
36

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

enter image description here

Articulate answered 2/11, 2020 at 17:2 Comment(4)
You are a genius. Just wasted an afternoon not able to find the error thanks.Capella
Thank you for this, great help in assisting my debugging.Afebrile
Using dev tools/developer tools is brilliant. ThanksPercent
Quite Easy and worked for meRussianize
W
22

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

Walking answered 15/3, 2021 at 8:23 Comment(4)
Thanks!!! my problem was a ODataController with the next error: No media types found in 'Microsoft.AspNet.OData.Formatter.ODataInputFormatter.SupportedMediaTypesEctophyte
/swagger/v1/swagger.json not foundAha
@Aha Did you change the configs of the Swagger?Walking
None changed. Finally, the error is method duplicated, but I don't know how to troubleshooting for view the error (any output, log, ...)Aha
I
12

I've been working with .NET 5 and I spent some time trying to understand what was going on.

I got an error like the one below:

Swagger Loading Error

Then I resolved this problem by the following:

Open startup.cs file Add the following code in Configure method

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger(c =>
        {
            c.RouteTemplate = "/swagger/{documentName}/swagger.json";
        });
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
    }

And in ConfigureServices method

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
        c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
    });

Thanks to TheCodeBuzz for Resolved: Failed to load API definition (undefined /swagger/v1/swagger.json)

Note the difference between the RouteTemplate string and the SwaggerEndpoint string. One uses {documentName} and the other uses "v1" as a literal.

Ingaingaberg answered 31/8, 2021 at 14:57 Comment(0)
Q
11

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")]
Quipster answered 27/4, 2021 at 16:2 Comment(0)
O
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);
        } 
Oliver answered 7/11, 2020 at 17:17 Comment(0)
O
7

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.

Ordzhonikidze answered 3/1, 2020 at 16:14 Comment(0)
A
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.

Annia answered 31/3, 2020 at 1:36 Comment(0)
A
3

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...

Acierate answered 21/8, 2020 at 18:16 Comment(0)
G
3

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/

Gilliland answered 29/4, 2021 at 9:46 Comment(0)
L
3

Here we go:

I created WEB Controller instead of WEB API Controller. That makes this kind of error. During creation of new Controller, make sure that you created right WEB API controller.

Lugsail answered 1/5, 2022 at 19:10 Comment(0)
T
2

Surely it is one of the Controller's method that is faulty. To get the method, at times you might need to take out all your controllers, Try and insert them one after the other then you will test along to find the Controller with bugs.

For ex. If you have like 3Controllers say

>Controller
>>>AuthController
>>>UserController
>>>HomeController

Take two out of the controllers out and test the controller by adding one controller after each successful testing. With that you will know the controller that has a faulty method.

>Controller
>>>AuthController
If the methods in AuthenController is fine, It will run, If not Check the methods.
>Controller
>>>AuthController
>>>UserController

and carry out the next check on the controller like that of Authen.

Therapist answered 16/12, 2021 at 4:50 Comment(0)
P
1

I had the same problem, so I checked it using inspect element on the browser. The "Console" tab shows the file where the problem originated from (v1/swagger/json:1). Opening it by clicking it showed that one of the helper methods I used in my controller was "Public". Changing it to "Private" fixed the problem for me.

This page also has good tips: https://btrehberi.com/swagger-failed-to-load-api-definition-fetch-error-undefined-hatasi-cozumu/yazilim/

Paleogeography answered 22/7, 2021 at 12:39 Comment(0)
N
1

Swagger in my case needed [HttpAction] with all public members in controller. Unfortunately I misspelled constructor name and since it was public, was throwing this error.

Nursling answered 23/7, 2021 at 8:4 Comment(0)
T
1

For ASP.NET Core 3.1 I had to ensure the verb were not ambiguous and I found this out by first running the API project without IIS in VS2019 (Green Arrow > left-click the carrot icon and select the name of the project this causes a console window to appear on start up so you can inspect what's happening and see errors).

[HttpGet("MyEndPointA")

Then Swagger is able to generate the documentation correctly.

Tsan answered 11/8, 2021 at 18:23 Comment(0)
O
1

Solved issue in dotNet 6! Just change the attribute order of [ApiController]

enter image description here

Ovarian answered 14/11, 2021 at 9:20 Comment(0)
S
0

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.

Supplicate answered 26/2, 2020 at 8:54 Comment(0)
M
0

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

Modernity answered 2/3, 2021 at 19:53 Comment(1)
Still a better solution is to decorate the class/controller that has released the error with ApiExplorerSettings (IgnoreApi = true)]Modernity
E
0

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

Expressionism answered 16/3, 2021 at 13:57 Comment(0)
C
0

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

Cockney answered 3/4, 2021 at 23:13 Comment(0)
I
0

<b>make sure the name "v1" matches the path in the swagger endpoint</b>
    <p>
    services.AddSwaggerGen(c =>
       {
     c.SwaggerDoc("v1", new OpenApiInfo { 
Title = "ODAAPP",  
Version = "v1" });
                });
                </p>
                <br/>

app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",
                             "ODAAPP v1"));

enter code here
Imre answered 19/8, 2021 at 20:26 Comment(0)
P
0

This will also happen if you use same route for multiple action methods (Overloading is OK)

Pelias answered 9/9, 2021 at 7:44 Comment(0)
D
0

In my case, the project was configured to authenticate using identity server 4 using AddPolicy() at startup.cs and there were usages of [Authorize]

I removed the things for startup.cs and usages of [Authorize]

Will update more soon

Dulin answered 5/11, 2021 at 10:22 Comment(0)
B
0

In my case I had two identicall inner classes. Extracted them to a single one refactored the namespaces and voilá, all returned to work properly.

Boeotia answered 5/1, 2022 at 14:57 Comment(0)
P
0

I have experienced the same error when I was using Swagger and also Microsoft.AspNetCore.OData. I usually try to use the latest version - but bringing it down to v 7.5.12 - did solve my issue.

Also adding following to every Action method in the Controller, makes it work with OData v8.x too: [HttpGet], [HttpPost], or [ApiExplorerSettings(IgnoreApi = true)]

Publication answered 8/2, 2022 at 1:47 Comment(0)
C
0

I had a similar Fetch error 404 swagger/v1/swagger.json, when trying to integrate Swagger documentation in ASP.NET Core 3.1 Web API project. I tried almost all of the above suggestions but failed. After an hour of hit-and-trial, I decided to give NSwag a try using this reference, instead of Swashbuckle and it just worked like a charm :)

Cirrate answered 12/2, 2022 at 17:50 Comment(0)
H
0

Reasons for this Error

i resolved this issue by this way Use [HttpGet] attribute above the api controller method.

And, because of different versions of swashbuckle, these errors may come.

you should use the correct swagger endpoint url

v1/swagger.json   or swagger/v1/swagger.json

choose above one based on the version you are using.

Note:

Use this url for reference https://myget.org/feed/domaindrivendev/package/nuget/Swashbuckle.AspNetCore.Swagger/6.2.3-preview-1963

Refer the official swagger documentation. lot of information is there with crystal clear documents https://swagger.io/docs/

Hunkers answered 9/3, 2022 at 16:31 Comment(0)
T
0

'Multiple operations with path 'some_path' and method 'GET' '

[HttpGet]
public IActionResult Get()
{
    return Ok(_userService.Get());
}

[HttpGet]
public IActionResult Get(int Id)
{
    return Ok(_userService.Get(Id));
}

Just modify DataAnnotation:

[HttpGet]
public IActionResult Get()
{
    return Ok(_userService.Get());
}

[HttpGet("{Id}"] //HERE
public IActionResult Get(int Id)
{
    return Ok(_userService.Get(Id));
}
Throat answered 18/3, 2022 at 16:43 Comment(0)
S
0

I had the same error and what fixed it was adding the[HttpGet] attributee in my controller

Saturninasaturnine answered 22/3, 2022 at 19:49 Comment(0)
I
0

When using springdoc and you face

Swagger Whitelabel Page Error

or

Swagger Blank Page Error

you can resolve the errors by

Adding springdoc Dependencies:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.9</version>
</dependency>

Removing Swagger and Spring Dependencies

Removing SwaggerConfigure or any related Annotation and File

Add these into the Security Config

-- > override configure method and add these

.antMatchers("/v2/api-docs",
             "/configuration/ui",
             "/swagger-resources/**",
             "/configuration/security",
             "/swagger-ui/**",
             "/webjars/**",
             "/v3/api-docs/**")

Lastly, add these in the application.properties file,

spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER

# swagger-ui custom path
springdoc.swagger-ui.path=/swagger-ui.html
Inna answered 4/8, 2022 at 17:19 Comment(0)
F
0

When you have the same name of API Endpoints in the same controller then it will give this error. Like that below in image Difference in Api Endpoints

Flicker answered 1/5, 2023 at 8:56 Comment(0)
F
-2

I got the similar issues - the root cause is I forgot to add the annotations :-(

Faller answered 8/3, 2022 at 15:0 Comment(1)
Which annotation and where?Grow

© 2022 - 2024 — McMap. All rights reserved.