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
print ?
  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. }  
using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Description;
namespace OwinConsoleApp
{
    /// <summary>
    /// 学生信息
    /// </summary>
    public class StudentController : ApiController
    {
        /// <summary>
        /// 得到所有的学生信息
        /// </summary>
        /// <returns></returns>
        public IEnumerable<string> Get()
        {
            return new List<string>() { "student A", "student B" };
        }
        /// <summary>
        /// 根据学生编号得到学生信息
        /// </summary>
        /// <param name="Id">学生编号</param>
        /// <returns></returns>
        public string Get(int Id)
        {
            return "学号:" + Id;
        }
        /// <summary>
        /// 添加学生
        /// </summary>
        /// <param name="studentModel">学生实体</param>
        /// <remarks>添加一个新的学生</remarks>
        /// <response code="400">Bad request </response>
        /// <response code="500">Internal Server Error</response>
        public void Post(String studentModel)
        {
        }
        /// <summary>
        /// 修改学生信息
        /// </summary>
        /// <param name="Id">学生编号</param>
        /// <param name="studentModel">学生实体</param>
        [ResponseType(typeof(string))]
        [ActionName("UpdateStudentById")]
        public void Put(int Id, string studentModel)
        {
        }
        /// <summary>
        /// 删除学生信息
        /// </summary>
        /// <param name="Id">学生编号</param>
        public void Delete(int Id)
        {
        }
    }
}

3、修改SwaggerConfig文件如下:

[csharp] view plain copy
print ?
  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. }  
using System.Linq;
using System.Web.Http;
using WebActivatorEx;
using OwinConsoleApp;
using Swashbuckle.Application;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace OwinConsoleApp
{
    public class SwaggerConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableSwagger(c =>
                    {
                        c.SingleApiVersion("v1", "");
                        c.IncludeXmlComments(GetXmlCommentsPath());
                        c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                    })
                .EnableSwaggerUi();
        }
        private static string GetXmlCommentsPath()
        {
            return System.String.Format(@"{0}\Swagger.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        }
    }
}
4、新建一个Startup文件,代码如下:

[csharp] view plain copy
print ?
  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. }  
using Owin;
using Microsoft.Owin;
using System.Web.Http;
using Swashbuckle.Application;
[assembly: OwinStartup(typeof(OwinConsoleApp.Startup))]
namespace OwinConsoleApp
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            SwaggerConfig.Register(config);
            appBuilder.UseWebApi(config);
        }
    }
}
5、修改program程序,代码如下:

[csharp] view plain copy
print ?
  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. }  
using System;
using Microsoft.Owin.Hosting;
namespace OwinConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:9000/";
            // Start OWIN host 
            using (WebApp.Start<Startup>(url: baseAddress))
            {
                Console.WriteLine("OWIN SERVICE OPEN!");
                Console.Read();
            }
            Console.ReadLine();
        }
    }
}

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



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

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



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

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





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值