使用Swagger和命名空间版本的Web Api

时间:2014-10-15 16:20:26

标签: c# asp.net-web-api swagger

我已经了解了如何使用this class基于命名空间对我的WebAPI进行版本化。

我正在使用Swashbuckle将swagger doc添加到我的API中,使用Swashbuckle Nuget包。

如果我保持一切完整,当我导航到/ swagger /时,我会得到一个空页。

在我的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);
    }
}

我的网络API路线:

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
                });
    }
}

如果我删除{namespace}它的工作原理(显示API命令),但我想在我的路线中保留这个命名空间信息。

如何自定义Swagger / Swashbuckle以使其正常工作?

1 个答案:

答案 0 :(得分:2)

来自Swashbuckle Github回购:

  

"命名空间路由"的上述实现存在缺陷。因为它打破了WebApi元数据层 - ApiExplorer,因此Swashbuckle。

解决方法虽然没有直接解决您的问题,但是使用属性版本控制,这适用于Swashbuckle:

即:

[RoutePrefix("api/v1/Features")]
public class FeaturesV1Controller : ApiController
{
    [Route("Products/{product}")]
     public IList<Metadata.FeatureListItemModel> Get(long product){}

有关详细信息,请参阅下面的两个Github问题。 https://github.com/domaindrivendev/Swashbuckle/issues/317 https://github.com/domaindrivendev/Swashbuckle/issues/303

我相信通过属性路由,您的控制器必须为每个版本指定不同的名称。即该类应该命名为FeaturesV1Controller和FeaturesV2Controller for v2,但对于路由你仍然可以使用/ api / v1 / Features和/ api / v2 / Features