.NetCore2.1 WebAPI新增Swagger插件
阿新 • • 發佈:2018-07-08
env 地址 build develop site defining key register 如何實現
說明
Swagger是一個WebAPI在線註解、調試插件,過去我們主要通過手工撰寫WebAPI接口的交互文檔供前端開發人員或外部開發者,
官網地址:https://swagger.io/。
但是在實際工作中,往往咋們的文檔工作通常落後於實際的環境,導致文檔和實際接口不一致,前後端開發人員苦不堪言。
Swagger的出現解放了接口文檔撰寫的麻煩也提高了前後端開發者的工作效率,所謂“工欲善其事,必先利其器 ”。現在讓咋們
了解下在.NET Core 2.1下如何實現Swagger。
1、Nuget安裝依賴包
首先Nuget安裝Swashbuckle.AspNetCore
打開Nuget控制臺(程序包管理控制臺),鍵入下列命令
Install-Package Swashbuckle.AspNetCore
2、添加Swagger中間件
public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().AddJsonOptions(options => { //忽略循環引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //不使用駝峰樣式的key options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); return RegisterAutofac(services);//註冊Autofac }
引用Swashbuckle.AspNetCore.Swagger,並啟用中間件
1 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 2 { 3 if (env.IsDevelopment()) 4 { 5 app.UseDeveloperExceptionPage(); 6 } 7 // Enable middleware to serve generated Swagger as a JSON endpoint.8 app.UseSwagger(); 9 // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 10 // specifying the Swagger JSON endpoint. 11 app.UseSwaggerUI(c => 12 { 13 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); 14 }); 15 app.UseVisitLogger(); 16 app.UseMvc(); 17 }
3、配置WebAPI項目屬性
1、雙擊Properties下的launchSettings.json,將launchUrl更新為swagger
F5結果如下:
.NetCore2.1 WebAPI新增Swagger插件