Swaggerui 可以为我们的webapi提供美观的在线文档,如下图:
实现步骤:
- NuGet Packages Install-Package Swashbuckle.AspNetCore
- 在startup文件中配置swagger
1 // Register the Swagger generator, defining one or more Swagger documents 2 services.AddSwaggerGen(c => 3 { 4 c.SwaggerDoc("v1", new Info 5 { 6 Version = "v1", 7 Title = "ToDo API", 8 Description = "A simple example ASP.NET Core Web API", 9 TermsOfService = "None",10 Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "https://twitter.com/spboyer" },11 License = new License { Name = "Use under LICX", Url = "https://example.com/license" }12 });13 14 //Set the comments path for the swagger json and ui.15 var basePath = PlatformServices.Default.Application.ApplicationBasePath;16 var xmlPath = Path.Combine(basePath, "MyWebApiCore.xml");17 c.IncludeXmlComments(xmlPath);18 });19 }20 21 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.22 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)23 {24 loggerFactory.AddConsole(Configuration.GetSection("Logging"));25 loggerFactory.AddDebug();26 27 app.UseMvc();28 app.UseSwagger();29 app.UseSwaggerUI(c =>30 {31 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");32 });33 }
- XML Comments,点击项目属性=》生成=》XML文档文件打勾,然后在你的action上添加注释
/// <summary>
/// Get方法无参数 /// </summary> /// <returns>string[]数组</returns> [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }/// <summary>
/// 根据id获取 /// </summary> /// <param name="id"></param> /// <returns></returns> /// <remarks> /// Note that the id is an integer. /// </remarks> [HttpGet("{id}")] public string Get(int id) { return "value"; } - 运行项目,输入文档地址http://localhost:58911/swagger/
你可以选择方法进行在线测试