Migrating to .NET Core 2.1 breaks Swagger UI
I know this has already been answered, however just thought I'd chime in for anyone who runs into this and still looking for an answer. If you try to go directly to the json file it will provide you a reason why it's not working.
Example:
In the Address Bar: https://localhost:44300/swagger/v1/swagger.json
Error Message Returned:
{"Path":"/swagger/v1/swagger.json","Started":false,"State":"Internal Server Error","Msg":"Ambiguous HTTP method for action - Controllers.ChatMessageController.ListFriends (Project.API). Actions require an explicit HttpMethod binding for Swagger 2.0"}
I tried to recreate the same solution line by line. Swagger worked until I added <PreserveCompilationContext>false</PreserveCompilationContext>
into the .csproj
file. Removing this attribute caused the Swagger UI to reappear.
I upgraded my project from 2.2 to 3.1 and was facing the same problem even after attempting all the steps provided. For some reasons, I didn't have the [ApiController]
above my controller class. When I added it, swagger document showed up...
With C# .Net core if you use several methods with the decorator [HttpPost] or [HttpGet] the /swagger/v1/swagger.json file cannot be generated obviously because of the ambiguity of all the POST or GET methods.
If, locally working fine but getting problem after IIS hosting then you have a problem with swagger.json
relative path.
Then try this below inside ConfigureServices
:
app.UseSwaggerUI(c =>
{
string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "My API");
});