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文件, 代码例如以下:

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文件例如以下:

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文件,代码例如以下:

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程序,代码例如以下:

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搞出来了,当初就是在版本号的差异上浪费了太多时间。

写此文章,与和我有同样经历的人共勉。文中若有纰漏,还请指出。





原文地址:https://www.cnblogs.com/cynchanpin/p/6909802.html