WebApi写好以后,在线帮助文档以及可以在线调试的工具是专业化的表现,而Swagger毫无疑问是作Docs的最佳工具,自动生成每一个Controller的接口说明,自动将参数解析成json,而且可以在线调试。html
那么要讲Swagger应用到Asp.net Core中须要哪些步骤,填多少坑呢?前端
{ "dependencies": { "Swashbuckle": "6.0.0-beta902", ........
或者直接经过NuGet界面来添加Swashbuckle,目前最新版本6.0.0-beta902git
1.startup.cs=>configureServicesgithub
//文档解析 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=>configureweb
//文档解析 app.UseSwagger(); app.UseSwaggerUi();
3.自动读取方法的描述信息ajax
参考文档:https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swaggerjson
全部配置作完后,直接访问http://xxx/swagger/ui 便可看到接口的界面了后端
可是默认的swagger UI我的认为仍是有点丑陋,部分细节处理不到位,swagger的全部资源文件都是嵌入型的,没法直接修改,虽然提供部分ui接口,但如何才能彻底自定义UI呢?api
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/