使用第三方提供的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搞出來了,當初就是在版本的差異上浪費了太多時間。寫此文章,與和我有相同經歷的人共勉。文中若有紕漏,還請指出。