在學習net core中接觸到了swagger、學習并記錄
純API專案中 引入swagger可以生成可視化的API介面頁面

引入包
nuget包: Swashbuckle.AspNetCore(最新穩定版)
配置
1.配置Startup類ConfigureServices方法的相關配置
1 public void ConfigureServices(IServiceCollection services) 2 { 3 //swagger服務配置 4 services.AddSwaggerGen(c => 5 { 6 c.SwaggerDoc("V1", new Microsoft.OpenApi.Models.OpenApiInfo 7 { 8 Version = "v1",//介面檔案版本 9 Title = "我的介面檔案1.0",//介面檔案標題 10 Description = "我的第一個swagger檔案",//介面檔案描述 11 Contact = new Microsoft.OpenApi.Models.OpenApiContact { Name = "張華", Url = new Uri("http://baidu.com"), Email = "[email protected]" }, 12 License = new Microsoft.OpenApi.Models.OpenApiLicense { Name = "張華", Url = new Uri("http://baidu.com") } 13 }); 14 }); 15 services.AddControllers(); 16 }1.配置Startup類ConfigureServices方法的相關配置
2.配置Startup類Configure方法的中間件
1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 2 { 3 if (env.IsDevelopment()) 4 { 5 app.UseDeveloperExceptionPage(); 6 } 7 8 app.UseRouting(); 9 10 app.UseAuthorization(); 11 12 app.UseEndpoints(endpoints => 13 { 14 endpoints.MapControllers(); 15 }); 16 17 ///swagger中間件啟動配置 18 app.UseSwagger(); 19 app.UseSwaggerUI(a => { 20 a.SwaggerEndpoint("/swagger/V1/swagger.json", "中間件啟動配置,我的第一個swagger檔案"); 21 //如果是為空 訪問路徑就為 根域名/index.html,注意localhost:8001/swagger是訪問不到的 22 //路徑配置,設定為空,表示直接在根域名(localhost:8001)訪問該檔案 23 // c.RoutePrefix = "swagger"; // 如果你想換一個路徑,直接寫名字即可,比如直接寫c.RoutePrefix = "swagger"; 則訪問路徑為 根域名/swagger/index.html 24 a.RoutePrefix = string.Empty;//路由 25 }); 26 }2.配置Startup類Configure方法的中間件
注意:
新建專案第一次配置完成運行的時候可能如下所示,因為 /WeatherForecast 是官方默認的地址

解決方案:Properties檔案夾下launchSettings.json檔案launchUrl屬性改為null
launchUrl代表瀏覽器里啟動相對的URL

Ps:個人小小理解,希望有錯誤可以指正
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453721.html
標籤:.NET Core
