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

 

以下为教程:

 

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

swagger.net.ui

swashbuckle

 安装完毕后可以卸载Swagger.NET,此处不需要!

安装完毕后屏蔽以下代码

直接运行调试

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

此时如果没有注释.

项目属性里添加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));

临时屏蔽即可

posted on 2017-12-14 16:48  火星大能猫  阅读(1582)  评论(0编辑  收藏  举报