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

落花浮王杯 提交于 2020-08-02 04:16:07

问题


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();
    }
}

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




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/56859604/swagger-not-loading-failed-to-load-api-definition-fetch-error-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!