Sounds easy right? But it turn to be very confusing. When I first tried to integrate Swashbuckle I met few problems:
- Auto generated documentation totally ignored existing and working API endpoints (methods in ApiControllers). So it was totally empty.
- After solving the first issue I realised that “/Token” endpoint is still not listed.
- Had to find a way to pass a bearer token with each request swagger generated for me.
So let’s start solving those problems one by one.
First we have to install Swashbuckle nuget package: Install-Package Swashbuckle
That should generate SwaggerConfig.cs under App_Start folder:
To solve problem #1 we need to use the right HttpConfiguration:
- Remove [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), “Register”)] from SwaggerConfig.cs__. We will register it manually.
- Change the signature of Register method to public static void Register(HttpConfiguration httpConfig)__. This will allow us to pass the right HttpConfiguration.
- Change GlobalConfiguration.Configuration to httpConfig.EnableSwagger. This will allow us to use the right HttpConfiguration upon the registration_._
Now we have to manually register our swagger, for that we just have to add one additional line to Startup.cs__;
At this point all our API endpoints should be visible if you navigate to http://yourapi:port/swagger
To solve problem number #2 we have to manually define documentation for our /Token endpoint by creating a AuthTokenDocumentFilter.cs (source):
The next step will be to add AuthTokenDocumentFilter to our swagger configuration:
At this point “Auth” endpoint will become visible at http://yourapi:port/swagger
To solve problem number #3 we have to make few small changes in SwaggerConfig.cs.
Add the next line inside EnableSwagger section:
Inside EnableSwaggerUi section add the next line:
Now in order to get a bearer token you can use swagger and if you want to use the retrieved token in all calls simply add it near the “Explore” button:
Good luck!
P.S.: You can get the file from GitHub Gist