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.
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):
public class AuthTokenDocumentFilter : IDocumentFilter { public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.paths.Add("/token", new PathItem { post = new Operation { tags = new List{ "Auth" }, consumes = new List { "application/x-www-form-urlencoded" }, parameters = new List { new Parameter { type = "string", name = "grant_type", required = true, @in = "formData", @default = "password" }, new Parameter { type = "string", name = "username", required = false, @in = "formData" }, new Parameter { type = "string", name = "password", required = false, @in = "formData" } } } }); }
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:
c.ApiKey("Token") .Description("Bearer token") .Name("Authorization") .In("header");
Inside EnableSwaggerUi section add the next line:
c.EnableApiKeySupport("Authorization", "header");
Good luck!
P.S.: You can get the file from GitHub Gist
thank you, it was very helpful
ReplyDeleteThe post is totally awesome! Bunches of incredible information and motivation the two of which we as a whole need! Likewise prefer to appreciate the time and effort you put into your blog.
ReplyDeleteDigital Marketing Training in Chennai
Digital Marketing Course in Chennai