1、建立一個Asp.NetCore WebApi 項目ios
2、引入NuGet包 SwashBuckle.AspNetCore json
3、在項目屬性配置中設置api
4、修改項目的啓動文件Startup.csapp
1)、在ConfigureServices方法中註冊Swagger中間件ui
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 4 5 services.AddSwaggerGen(sg=>{ 6 sg.SwaggerDoc("v1", new Info() 7 { 8 Version="1.0.0", 9 Title="WebApi", 10 Description = "WebApi接口說明文檔", 11 TermsOfService = "None", 12 Contact = new Contact 13 { 14 Name = "你是個人四月天", 15 Email = "993484167@qq.com", 16 Url = "https://www.cnblogs.com/awaTangjay/" 17 } 18 }); 19 sg.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "WebApi.xml"));//WebApi.xml是在項目屬性配置中配置的xml文件名 20 }); 21 }
2)、在Configure方法啓用Swagger中間件this
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.UseHttpsRedirection(); app.UseMvc(); app.UseSwagger(s => s.RouteTemplate="swagger/{documentName}/swagger.json"); app.UseSwaggerUI(s => { s.SwaggerEndpoint("v1/swagger.json","v1.0.0"); });//這個v1對應SwaggerDoc中的name v1 }
5、給控制器前加上路由spa
[Route("api/[controller]/[Action]")] [ApiController] public class ValuesController : ControllerBase {
6、ctrl+F5 調試WebApi3d
在域名後面輸入swagger 回車調試