How to customize Swagger UI in dotnet core Web API
Swagger is used to describe the REST web api. For regular XML base WCF application the web service can be discovered using wsdl which is not applicable for RESTful web api. Here Swagger come into picture. It help to understand what is the end point exposed by the web api, what kind of input, output format it use. In this Tutorial you will see how to customize Swagger UI in asp.net web api.
Required tools used for this sample application
- Windows 10
- MS Visual Studio Community Edition 2019
- dotnet core 3.1[LTS]
- Swashbuckle.AspNetCore version 6.2.3
Create a dotnet core Web api application
Add dotnet core package reference for Swashbuckle.AspNetCore -Version 6.2.3
Add Swagger generator to Startup.cs. In some cases you can add to program.cs. In that case use builder object to add to Swagger generator middleware.
Add the swagger based upon running environment config. It is not necessary to use only for Development config. It can be used for any other runtime environment configuration also.
Here we are done with basic setup for Swagger for dotnet core web api. If you run the application from Visual Studio, you should be able to view below screen.
Now we see how we can add some more customization to the Swagger UI.
Set the Router prefix to null so that it can render to root of the api
Add the following code in Startup.cs. in case of IIS is set with reverse proxy then use ./ prefix in the path i.e. ./swagger/v1/swagger.json
Now lets see how the output looks like. Run the web api from visual studio. note the URL in this case became https://localhost:44355/index.html
Add api description and information
Add the following line of code in SwaggerGen
Swagger Api Description |
Now lets see how the Swagger UI would looks like. Here the Custom details has been included in Swagger UI
Enable XML commenting in Swagger
1. Enable xml documentation for you proj file as following
2. In Startup.cs file add following line of code and add some xml in controller method,
Lets see the output now. you can see the xml comment is showing in the description
Few more with XML commenting use remarks tag and describe the output type
Add the below xml comment.
Lets see the output by running the project,
Set Media Type
add the following code above the controller method,
Lets see the output in browser,
Reference URL for further study:
End Of Document