If you’ve ever worked with webservices, chances are you’ve run into WSDL (http://www.w3.org/TR/wsdl). In the webapi world you don’t get so much out the box – this is where swagger can help expose test methods, documentation and a lot more.
For asp.net projects you can make use of a library: https://github.com/domaindrivendev/Swashbuckle. Install via nuget and you get a UI allowing a configurable interaction with all the webapi methods in your solution:
The test controller and methods:
All pretty simple stuff – how about if you want to secure things?
An example scenario might be you only want swagger accessible if you are visiting via http://localhost (or a loopback url).
It’s straight forwards if you implement a custom webapi DelegatingHandler.
using System.Net.Http; using System.Security; using System.Threading; using System.Threading.Tasks; namespace SwaggerDemo.Controllers.Api { public class SwaggerAccessHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request.RequestUri.ToString().ToLower().Contains("/swagger/")) { if (IsTrustedRequest(request)) { return await base.SendAsync(request, cancellationToken); } else { throw new SecurityException(); } } return await base.SendAsync(request, cancellationToken); } private bool IsTrustedRequest(HttpRequestMessage request) { //concoct the logic you require here to determine if the request is trusted or not // an example could be: if request.IsLocal() return true; } } }
This then needs wiring into the webapi request pipelines. In your WebApiConfig file (OTB in your solution in the folder: App_Start) add:
config.MessageHandlers.Add(new SwaggerAccessHandler());
In the TestController example above we had several httpPost methods available – to enable this functionality you need to allow the routes to include the {action} url chunk.
config.Routes.MapHttpRoute( name: "DefaultApiWithAction", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );
Azure webapi’s are now compatible with swagger – see https://azure.microsoft.com/en-gb/documentation/articles/app-service-dotnet-create-api-app/ for more info.
The post Documenting webapi with Swagger appeared first on blog.boro2g.co.uk.