ASP.NET Web API 使用Swagger生成在线帮助测试文档,支持多个GET

 

如下为教程:web

 

在现有webapi项目中,nuget安装如下两个插件json

swagger.net.uiapi

swashbuckle浏览器

 安装完毕后能够卸载Swagger.NET,此处不须要!fetch

安装完毕后屏蔽如下代码ui

直接运行调试url

在浏览器的目录后面加上/swagger便可跳转到swagger调试页spa

此时若是没有注释..net

项目属性里添加xml注释的生成插件

修改App_Start下的SwaggerConfig.cs文件

 添加以下代码

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {
                        c.IncludeXmlComments(GetXmlCommentsPath());
......
}

 

  protected static string GetXmlCommentsPath()
        {
            return System.String.Format(@"{0}\bin\你的xml文件名.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        }

此时从新生成浏览能够获取正确的注释并调试了.

 异常解决

报错

webapi 配置swagger出现问题:

Swagger Not supported by Swagger 2.0: Multiple operations with path 解决方法

一个controller中只能有一个HttpGet请求,多了就会报错。建议减小重载方法,将其余Get方法分开

若是在swagger.config中加上c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());则会只显示第一个get方法

 

异常2

加了上面的方法后,get可能会只显示一条记录

WebAPI 默认只支持一个get方法,支持多个Get须要修改

RouteConfig文件

   routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

 

所以,须要对swagger.net也添加相应的支持.

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            RouteTable.Routes.MapHttpRoute(
               name: "SwaggerApi",
               routeTemplate: "api/docs/{controller}/{action}",
               defaults: new { swagger = true }
           );
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

以上

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                //   routeTemplate: "api/{controller}/{id}",
                routeTemplate: "api/{controller}/{action}/{id}",
                  //defaults: new { id = RouteParameter.Optional }
                  defaults: new { controller = "Home", action = "Index", id = RouteParameter.Optional }
            );

 

 

完成

 

异常3

fetching resource list: http://localhost:8011/swagger/docs/v1; Please wait.

一直显示这个界面

 

只返回Json Result的content negotiation代替Web Api中默认的content negotiation形成的.

WebApiConfig

config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

临时屏蔽便可

相关文章
相关标签/搜索