After changing our ASP.NET Core application to no longer run under the root site(e.g. https://localhost/) but under a virtual directory instead (e.g. https://localhost/mysampleapp/) , loading the API definitions in Swagger no longer worked and failed with the following error message:
Fetch error undefined swagger/v1/swagger.json
To fix the problem, I had to do 2 things:
First I updated the Swagger json generation to set the SwaggerDoc to a specific path. Although the documentation mentions the first parameter of SwaggerDoc as the name, it becomes part of the URI of your swagger.json file.
In this case I set the name to ‘v1’:
services.AddSwaggerGen(options => | |
{ | |
options.SwaggerDoc("v1", new Info | |
{ | |
Version = "v1", | |
Title = "Sample API", | |
Description = "API Sample", | |
TermsOfService = "None" | |
}); |
As a second step, I had to update the Swagger UI configuration to generate the swagger endpoint on a relative path. Important here is that the name of the swagger doc matches part of the URI before the swagger.json; in our case ../swagger/v1/swagger.json
app.UseSwaggerUI(c => | |
{ | |
c.SwaggerEndpoint("../swagger/v1/swagger.json", "V1 Docs"); | |
}); |