最近寫了好多Web api, 老大說太亂了,要整理一下,使用Swagger。
花了半天的時間,在這裏記錄和分享一些過程和遇到的問題。html
遇到的主要問題:
1.localhost:9040/swagger/ not foundgit
2.http://localhost:9040/swagger界面能夠打開,可是can't read json file.github
這裏引用了三個庫,都是在Nuget上安裝:
1.Microsoft.AspNetCore.StaticFiles, Version="2.0.3" , 這個package提供UI顯示相關服務
2.Swashbuckle.AspNetCore, Version="2.4.0"
3.Swashbuckle.AspNetCore.SwaggerUi, Version="2.4.0"web
using Swashbuckle.AspNetCore.Swagger;
在ConfigureServices集合中注入AddSwaggerGen:json
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Enable CORS services.AddCors(); //Inject Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "MyApi", Version = "v1" }); // Set the comments path for the Swagger JSON and UI. var xmlPath = Path.Combine(AppContext.BaseDirectory, "ChatBotApi.XML"); c.IncludeXmlComments(xmlPath); }); }
在Configure中啓用中間件,容許Swagger提供服務生成json文檔以及UI:swift
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseStaticFiles(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; }); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { //c.RoutePrefix = "swagger/ui"; c.SwaggerEndpoint("v1/swagger.json", "ChatBotApi"); }); }
在 Visual Studio 中右擊項目而且選擇 Properties 在 Output Settings 區域下面點擊 XML Documentation file 。api
這時候編譯項目,會出現不少warning,提示api沒有註釋,在每一個Api controller上方,連續輸入三個'/',便可將api的對應信息補充完整,要給每一個Api route加上 http的請求方式。
在各個Api里加上註釋:瀏覽器
/// <summary> /// Put value by id and value /// </summary> /// <param name="id">id</param> /// <param name="value">value</param> /// PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { }
1.在瀏覽器中輸入:http://localhost:/swagger/v1/swagger.jsonapp
返回Json文檔:
用json viewer打開json文件:
2.在瀏覽器輸入:http://localhost:9040/swagger/
到此說明配置Swagger成功。
詳細的API列表和文檔說明:
1.RoutePrefix
這是個坑,要好好匹配當前的項目路徑,否則UI打不開
2.SwaggerEndpoint
這是個坑,也是同樣,若是路徑匹配錯誤,UI打開了可是讀取json文檔失敗。
這兩個路徑配置能夠多試幾回,我嘗試了幾十次~~
這個暫時沒有作,今天太晚了,佔個位置~
1.Get started with Swashbuckle and ASP.NET Core
2.Swagger .NETCORE can't read json
3.ASP.NET Core 中文文檔