首页 文章

ASP.NET Web Api中的Swashbuckle被嵌套控制器搞糊涂了

提问于
浏览
4

在我的ASP.NET Web Api(ASP.NET 4 MVC 5)应用程序中,我有两条路由配置如下:

// Default route. Comes "out of the box" with Web Api.
        // e.g. api/users/123
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // A route for child controllers. See for example the LockController 
        // that is "nested" under the "UsersController".
        // e.g. api/users/123/lock
        config.Routes.MapHttpRoute(
            name: "ChildApi",
            routeTemplate: "api/{parentController}/{parentId}/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

这些实际上工作得很好,因为我有一个匹配第一条路线的"top level" UsersController 和一条与第二条路线匹配的"child" LockController (在 Users 文件夹中) .

现在我已经将Swashbuckle 5Swagger for .net)添加到我的应用程序中,Swagger很困惑地显示我实现的每个方法的两个路由 . 例如:

enter image description here

所以Swagger将 LockController 识别为顶级控制器和子控制器 .

我如何告诉Swagger特定控制器是顶级还是孩子?

另外,我可以让swagger认识到锁定资源的路径,例如,当Swagger正在显示时,它是 /api/users/{id}/lock 而不是 /api/{parentController}/{parentId}/lock 吗?

2 回答

  • 1

    我认为这应该有效 -

    config.Routes.MapHttpRoute("childapi", 
         "api/{Parent}/{i}/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional });
    

    适用于 -

    http://localhost:60953/api/Another/1/Child/GetFlag/poo
    
    http://localhost:60953/api/Parent/1/Child/GetFlag/poo
    
    http://localhost:60953/api/Child/1/Another/GetString/test
    
  • -1

    我认为问题与继承层次结构无关 . Swashbuckle为每个路由映射生成路由 . 为了防止Swashbuckle生成重复的路由,一个解决方案可能是添加控制器约束到路由 . 我希望这会有所帮助 .

    config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { controller = "Users" }
            );
    
              config.Routes.MapHttpRoute(
                name: "ChildApi",
                routeTemplate: "api/{parentController}/{parentId}/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { controller = "Lock" }
    
            );
    

相关问题