WebApi寫好之后,在線幫助文檔以及能夠在線調試的工具是專業化的表現,而Swagger毫無疑問是做Docs的最佳工具,自動生成每個Controller的接口說明,自動將參數解析成json,並且能夠在線調試。
那么要講Swagger應用到Asp.net Core中需要哪些步驟,填多少坑呢?
安裝Swagger到項目
{ "dependencies": { "Swashbuckle": "6.0.0-beta902", ........
或者直接通過NuGet界面來添加Swashbuckle,目前最新版本6.0.0-beta902
配置Swagger
1.startup.cs=>configureServices
//文檔解析 services.AddSwaggerGen(); //非必須 services.ConfigureSwaggerGen(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "UFX.Mall商城對接企業內部系統服務中間件接口說明文檔"+Configuration.GetValue<string>("Customer"), Description = "Based on Asp.net Core WebApi,Powered By 柚凡信息科技 www.cnunify.com" }); });
2.startup.cs=>configure
//文檔解析 app.UseSwagger(); app.UseSwaggerUi();
3.自動讀取方法的描述信息
參考文檔:https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger
重點:如何自定義Swagger的UI
所有配置做完后,直接訪問http://xxx/swagger/ui 即可看到接口的界面了
但是默認的swagger UI個人認為還是有點丑陋,部分細節處理不到位,swagger的所有資源文件都是嵌入型的,無法直接修改,雖然提供部分ui接口,但如何才能完全自定義UI呢?
swagger是前后端完全分離的項目,前端靜態文件通過ajax,請求json數據,返回接口的解析顯示到頁面上,swagger-ui可以在git中找到:https://github.com/swagger-api/swagger-ui/
將swagger-ui下載到本地,然后將dist里的所有文件放在wwwroot->swagger->ui
然后配置讓asp.net core自動讀取wwwroot的真實路徑。
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); //配置NLog loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); //異常處理中間件 app.UseMiddleware(typeof(ExceptionHandlerMiddleWare)); app.UseMvc(); // Enable static files middleware. app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); //文檔解析 app.UseSwagger(); app.UseSwaggerUi(); }
這樣,所有swagger文件都在本地了,想怎樣自定義都可以,show一下修改過的UI
當webapi發布到服務器,訪問的時候右下角swagger會有一個異常錯誤,要取消該錯誤,只需要將index.html里加入validatorUrl設置為null,取消對url的驗證即可
window.swaggerUi = new SwaggerUi({ url: url, validatorUrl: null, dom_id: "swagger-ui-container",
參考文檔:http://stackoverflow.com/questions/27808804/swagger-ui-shows-error-validation-when-deployed
同時swagger還提供一個接口文檔編輯器swagger-editor,可以方便的編輯swagger.json,編輯好了可以導出到工程中
http://editor.swagger.io/