Swagger是一個把api和註釋生成一個可視(或可訪問)的輸出工具,關且還能夠進行手工測試咱們的api,解決了程序不想寫文檔的問題(哈哈)。css
Swashbuckle.AspNetCore是用來解決asp.net core下的api文檔,不但能稱顯UI,還能夠在UI上進行測試。html
若是在asp.net core中使用swagger,首先在nuget下安裝Swashbuckle.AspNetCore,不過如今是預覽版,必定要把「包括預發行版」打上勾。git
同時還要添加三個引用:github
Swashbuckle.AspNetCore.SwaggerGen是生成Swagger文檔的組件json
Swashbuckle.AspNetCore.Swagger:是把Swagger文檔生成Json Api的組件c#
Swashbuckle.AspNetCore.SwaggerUI,是把Json Api轉成頁面的組件api
接下來設置項目屬性,生成-Output節點的XML documentation file打上勾,用來保證能把action上的註釋生成xml文檔。app
同時,Controller中的action都要加http特性,這樣方例生成swagger文檔時能找到準確的api,這點很重要asp.net
接下來,就要在Starup中去調置Swagger的使用了dom
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Swagger測試", Version = "v1", Description = "Swagger測試RESTful API ", TermsOfService = "None", Contact = new Contact { Name = "桂素偉", Email = "axzxs2001@163.com" }, }); //設置xml註釋文檔,注意名稱必定要與項目名稱相同 var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "SwaggerDemo.xml"); c.IncludeXmlComments(filePath); //處理複雜名稱 c.CustomSchemaIds((type) => type.FullName); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); app.UseSwagger(c => { //設置json路徑 c.RouteTemplate = "docs/{documentName}/swagger.json"; }); app.UseSwaggerUI(c => { //訪問swagger UI的路由,如http://localhost:端口/docs c.RoutePrefix = "docs"; c.SwaggerEndpoint("/docs/v1/swagger.json", "Swagger測試V1"); //更改UI樣式 c.InjectStylesheet("/swagger-ui/custom.css"); //引入UI變動js c.InjectOnCompleteJavaScript("/swagger-ui/custom.js"); }); }
關於更多的UseSwagger參數和UseSwaggerUI參數可參考
https://github.com/domaindrivendev/Swashbuckle.AspNetCore
設置中的custom.css和custom.js以下
custom.css
.logo__title { font-weight:bold; font-size:0.8em; }
custom.js
var titles=document.getElementsByClassName("logo__title"); titles[0].innerHTML = "Swagger測試";
關於美化UI能夠運行,查看具體的html Elements,而後去寫css或js
代碼參考:https://github.com/axzxs2001/Asp.NetCoreExperiment