Guest HridayDutta Posted August 30 Posted August 30 When hosting an ASP.NET Core API, it’s not uncommon to encounter the "Failed to load API definition" error in SwaggerUI. This article will explore the reasons behind this error and provide steps to resolve it. Problem You have an ASP.NET Core API with Swagger OpenAPI, and used the following code snippet to add and configure Swagger middleware. //adding swagger middleware builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //enable the middleware for serving the generated JSON document and the Swagger UI, app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "DemoAPI v1"); }); After deploying the application in IIS as a site, everything works fine, and Swagger UI functions correctly. However, when the same application is deployed under an existing site as an application, you start encountering the "Failed to load API definition" error. In the example below, the API is hosted under the "ExceptionLab" site and is listening on port 82. [ATTACH type=full" alt="HridayDutta_0-1724954969706.png]64132[/ATTACH] Browsing the Swagger endpoint of the API results in the "Failed to load API definition" error. [ATTACH type=full" alt="HridayDutta_1-1724955014672.png]64133[/ATTACH] Cause The root cause of this issue lies in the Swagger Endpoint definition. If you inspect it in the developer console, you’ll see a 404 error indicating that /swagger/v1/swagger.json was not found. [ATTACH type=full" alt="HridayDutta_2-1724955083119.png]64134[/ATTACH] The Swagger UI is correctly pointing to localhost:82/API, but the page is trying to retrieve the swagger.json from the parent site, which causes the error. Solution Resolving this issue is straightforward. You need to update the Swagger endpoint definition. You can either remove the SwaggerEndpoint entirely and allow the application to determine the correct URL automatically (though this removes customization options), or you can update the endpoint as follows: app.UseSwaggerUI(c => { c.SwaggerEndpoint("../swagger/v1/swagger.json", "DemoAPI v1"); }); Add two extra dots ".." at the beginning of the path, as shown in the example above. This adjustment should resolve the "Failed to load API definition" error by accurately pointing to the swagger.json file, ensuring that SwaggerUI loads correctly. Continue reading... Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.