文檔源地址 http://www.68idc.cn/help/makewebs/qitaasks/20160621620667.html
Swagger-UI本身只提供在線測試功能,要集成它還需要告訴它本項目提供的各種服務和參數信息。這里就需要一些工作量了,不過好在許多第三方庫已經給我們完成了這一工作。我這里用的是Swashbuckle,使用它也比較簡單,直接使用Nuget添加其程序包即可:
1、初始化包 PM> Install-Package Swashbuckle
增加該程序包時,它本身會把自己相應的一些注冊的代碼添加到項目中,雖然我們可以不太關心這些操作,但有的時候還是需要修改一些相關的配置的。
2、初始化包后App_Start會添加 ,SwaggerConfig 代碼如下:
using System.Web.Http; using WebActivatorEx; using WebApp; using Swashbuckle.Application; [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace WebApp { public class SwaggerConfig { public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "WebApp"); }) .EnableSwaggerUi(c => { GetXmlCommentsPath(); }); } private static string GetXmlCommentsPath() { return $@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\WebApi.XML"; } } }
3、集成XML注釋
api 應用 ->右鍵->屬性->生成->輸出-配置XML
4、運行程序 地址欄請求:http://localhost:5746/swagger/ 逼格很高啊
到此第一種方法完成
開始改造第一種方法 刪除SwaggerConfig ,修改Startup 代碼如下:
public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); config.EnableSwagger(c => { c.SingleApiVersion("v1", "WebAPI"); c.IncludeXmlComments(GetXmlCommentsPath()); c.ResolveConflictingActions(x => x.First()); }).EnableSwaggerUi(); app.UseWebApi(config); } private static string GetXmlCommentsPath() { return $@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\WebApi.XML"; }