Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Swagger with a namespaced-versioned WebApi

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?

like image 209
thomasb Avatar asked Oct 15 '14 16:10

thomasb


1 Answers

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

like image 174
Hoppe Avatar answered Sep 28 '22 10:09

Hoppe