将Swagger与名称空间版本的WebApi一起使用

tho*_*asb 8 c# asp.net-web-api swagger

我已经找到了如何使用这个类基于名称空间对我的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的网络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
                });
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我删除{namespace}它工作(显示API命令),但我想在我的路由中保留此命名空间信息.

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

Hop*_*ppe 3

来自 Swashbuckle Github 存储库:

上述“命名空间路由”的实现存在一个缺陷,因为它破坏了 WebApi 元数据层 - ApiExplorer,从而破坏了 Swashbuckle。

虽然不能直接解决您的问题,但解决方法是使用属性版本控制,这与 Swashbuckle 配合良好:

IE:

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

请参阅下面的两个 Github 问题以获取更多信息。 https://github.com/domaindrivendev/Swashbuckle/issues/317 https://github.com/domaindrivendev/Swashbuckle/issues/303

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