ASP.NET Web Api 2 接口API文档美化之Swagger

使用第三方提供的swgger ui 可有效提高 web api 接口列表的阅读性,并且可以在页面中测试服务接口。

但本人在查阅大量资料并进行编码测试后,发现大部分的swagger实例并不能有效运行。例如如下两个网址:http://www.cnblogs.com/caodaiming/p/4156476.html 和 http://bitoftech.net/2014/08/25/asp-net-web-api-documentation-using-swagger/。经过本人的一番折腾,最终发现,原来是由版本的差异导致的(以上两个例子在4.2.0版本下运行成功,读者可自行测试)。哎,要是这些作者能够标出插件包的版本,真能省下很多功夫。

目前Swashbuckle的最新稳定版本为5.2.1版。这个版本的编码方式与4.2.0版本有一定差异,本文也以5.2.1版本为例进行说明。

注:本文使用OWIN来自寄宿(self-host) web api,不清楚的读者可参考:http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api。

1、新建一个控制台应用程序OwinConsoleApp。Nuget分别添加Swashbuckle(5.2.1版本)和Microsoft.AspNet.WebApi.OwinSelfHost。添加Swashbuckle时,会在项目中自动添加App_Start文件夹和一个文件名为“SwaggerConfig”的文件。

2、新建一个StudentController文件, 代码如下:

[csharp]  view plain  copy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web.Http;  
  4. using System.Web.Http.Description;  
  5. namespace OwinConsoleApp  
  6. {  
  7.     /// <summary>  
  8.     /// 学生信息  
  9.     /// </summary>  
  10.     public class StudentController : ApiController  
  11.     {  
  12.         /// <summary>  
  13.         /// 得到所有的学生信息  
  14.         /// </summary>  
  15.         /// <returns></returns>  
  16.         public IEnumerable<string> Get()  
  17.         {  
  18.             return new List<string>() { "student A", "student B" };  
  19.         }  
  20.         /// <summary>  
  21.         /// 根据学生编号得到学生信息  
  22.         /// </summary>  
  23.         /// <param name="Id">学生编号</param>  
  24.         /// <returns></returns>  
  25.         public string Get(int Id)  
  26.         {  
  27.             return "学号:" + Id;  
  28.         }  
  29.         /// <summary>  
  30.         /// 添加学生  
  31.         /// </summary>  
  32.         /// <param name="studentModel">学生实体</param>  
  33.         /// <remarks>添加一个新的学生</remarks>  
  34.         /// <response code="400">Bad request </response>  
  35.         /// <response code="500">Internal Server Error</response>  
  36.         public void Post(String studentModel)  
  37.         {  
  38.         }  
  39.         /// <summary>  
  40.         /// 修改学生信息  
  41.         /// </summary>  
  42.         /// <param name="Id">学生编号</param>  
  43.         /// <param name="studentModel">学生实体</param>  
  44.         [ResponseType(typeof(string))]  
  45.         [ActionName("UpdateStudentById")]  
  46.         public void Put(int Id, string studentModel)  
  47.         {  
  48.         }  
  49.         /// <summary>  
  50.         /// 删除学生信息  
  51.         /// </summary>  
  52.         /// <param name="Id">学生编号</param>  
  53.         public void Delete(int Id)  
  54.         {  
  55.         }  
  56.     }  
  57. }  

3、修改SwaggerConfig文件如下:

[csharp]  view plain  copy
 
  1. using System.Linq;  
  2. using System.Web.Http;  
  3. using WebActivatorEx;  
  4. using OwinConsoleApp;  
  5. using Swashbuckle.Application;  
  6. [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]  
  7. namespace OwinConsoleApp  
  8. {  
  9.     public class SwaggerConfig  
  10.     {  
  11.         public static void Register(HttpConfiguration config)  
  12.         {  
  13.             config.EnableSwagger(c =>  
  14.                     {  
  15.                         c.SingleApiVersion("v1", "");  
  16.                         c.IncludeXmlComments(GetXmlCommentsPath());  
  17.                         c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());  
  18.                     })  
  19.                 .EnableSwaggerUi();  
  20.         }  
  21.         private static string GetXmlCommentsPath()  
  22.         {  
  23.             return System.String.Format(@"{0}\Swagger.XML", System.AppDomain.CurrentDomain.BaseDirectory);  
  24.         }  
  25.     }  
  26. }  

4、新建一个Startup文件,代码如下:

[csharp]  view plain  copy
 
  1. using Owin;  
  2. using Microsoft.Owin;  
  3. using System.Web.Http;  
  4. using Swashbuckle.Application;  
  5. [assembly: OwinStartup(typeof(OwinConsoleApp.Startup))]  
  6. namespace OwinConsoleApp  
  7. {  
  8.     public class Startup  
  9.     {  
  10.         public void Configuration(IAppBuilder appBuilder)  
  11.         {  
  12.             // Configure Web API for self-host.   
  13.             HttpConfiguration config = new HttpConfiguration();  
  14.             config.Routes.MapHttpRoute(  
  15.                 name: "DefaultApi",  
  16.                 routeTemplate: "api/{controller}/{id}",  
  17.                 defaults: new { id = RouteParameter.Optional }  
  18.             );  
  19.             SwaggerConfig.Register(config);  
  20.             appBuilder.UseWebApi(config);  
  21.         }  
  22.     }  
  23. }  

5、修改program程序,代码如下:

[csharp]  view plain  copy
 
  1. using System;  
  2. using Microsoft.Owin.Hosting;  
  3. namespace OwinConsoleApp  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             string baseAddress = "http://localhost:9000/";  
  10.             // Start OWIN host   
  11.             using (WebApp.Start<Startup>(url: baseAddress))  
  12.             {  
  13.                 Console.WriteLine("OWIN SERVICE OPEN!");  
  14.                 Console.Read();  
  15.             }  
  16.             Console.ReadLine();  
  17.         }  
  18.     }  
  19. }  

6、右键项目属性,在属性的“生成”中设置输出文档:


注:这里的XML文件路径和文件名应与SwaggerConfig文件中的配置保持一致。

7、管理员身份运行程序。在浏览器中输入如下地址:http://localhost:9000/swagger,显示如下页面:


点击相应的服务,在显示的框中输入对应的信息,再点击“Try it out!”,即可成功调用服务,并可查看返回的结果。

后话:搞了两天,终于把swagger搞出来了,当初就是在版本的差异上浪费了太多时间。写此文章,与和我有相同经历的人共勉。文中若有纰漏,还请指出。

猜你喜欢

转载自www.cnblogs.com/twinhead/p/9193949.html