I have found out how to version my WebAPI based on namespaces using this class.
I am using Swashbuckle to add Swagger doc to my API, using the Swashbuckle Nuget package.
If I keep everything intact, when I navigate to /swagger/, I get an empty page.
In my App_Start:
public class SwaggerConfig
{
public static void Register()
{
Bootstrapper.Init(GlobalConfiguration.Configuration);
SwaggerSpecConfig.Customize(c =>
{
c.IncludeXmlComments(GetXmlCommentsPath());
});
}
private static string GetXmlCommentsPath()
{
return string.Format(@"{0}\App_Data\XmlDocumentation.xml", AppDomain.CurrentDomain.BaseDirectory);
}
}
And my web API routes:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{namespace}/{controller}/{id}",
defaults: new
{
id = RouteParameter.Optional
});
}
}
If I remove the {namespace}
it works (the API commands are displayed), but I want to keep this namespace information in my route.
How do I customize Swagger/Swashbuckle to make this work?
From the Swashbuckle Github repo:
There is a flaw in the above implementation of "namespace routing" as it breaks the WebApi metadata layer - ApiExplorer and hence Swashbuckle.
A workaround, although doesn't directly solve your problem, is to use attribute versioning instead, which works fine with Swashbuckle:
I.e.:
[RoutePrefix("api/v1/Features")]
public class FeaturesV1Controller : ApiController
{
[Route("Products/{product}")]
public IList<Metadata.FeatureListItemModel> Get(long product){}
Please see the two Github issues below for more info. https://github.com/domaindrivendev/Swashbuckle/issues/317 https://github.com/domaindrivendev/Swashbuckle/issues/303
I believe that with attribute routing, your controller must have a different name for each version. I.e. the class should be named FeaturesV1Controller and FeaturesV2Controller for v2, but for the routes you can still use /api/v1/Features and /api/v2/Features
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With