使用Swagger服務搭建.Net Core API

使用Swagger服務搭建.Net Core API

建立.Net Core API

新建項目。文件——新建——項目ios

 

 

 

選擇應用程序模板。

設置存放路徑,命名方案名稱。json

 

 

建立API。app

 

 

 

搭建成功。ui

 

 

 

使用Swagger服務

添加引用

右鍵依賴項this

 

 

 

搜索服務並安裝。安裝好以後,在NuGet下會新增該包。spa

 

 

在Startup.cs下的ConfigureServices方法中添加服務。

 

 

public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); // c.IncludeXmlComments(xmlPath);
 }); }

 

在Startup.cs類下的Configure方法中使用服務。

 

public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
 app.UseHsts(); } app.UseSwagger(); //啓用中間件服務對swagger-ui,指定Swagger JSON終結點
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseHttpsRedirection(); app.UseMvc(); }

 

最後修改Properties文件夾下的launchSettings.json文件

 

 

運行成功。3d

相關文章
相關標籤/搜索