什么是Swagger
Swagger可以从不同的代码中, 根据注释生成API信息, swagger拥有强大的社区, 并且对于各种语言都支持良好, 有很多的工具可以通过swagger生成的文件生成API文档
.Net Core中使用
.Net Core中使用, 首先要用nuget引用Swashbuckle. AspNetCore, 在startup.cs中加入如下代码
Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Hello", Version = "v1" }); var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "WebApplication2.xml"); c.IncludeXmlComments(xmlPath); }); services.AddMvcCore().AddApiExplorer(); }
public void Configure(IApplicationBuilderapp, IHostingEnvironment env) { if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
app.UseMvcWithDefaultRoute(); app.UseSwagger(c => {
}); app.UseSwaggerUI(c => { c.ShowExtensions(); c.VaildatorUrl(null);
c.SwaggerEndpoint("/swagger/v1/swagger.json", "test V1"); }); }
|
以上部分为加载swagger的代码, 位于startup.cs中, 下面是controller代码
ValuesController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc;
namespace WebApplication2.Controllers { [Route("api/[controller]/[action]")] public class ValuesController : Controller { [HttpGet] public IEnumercble<string> Get() { return new string[] { "value1", "value2" }; }
[HttpGet("{id}")] public string Get(int id) { return "value"; }
[HttpPost] public void Post([FromBody]string value) {
}
[HttpPut("{id}")] public void Put(int id, [FromBody]string value) {
}
[HttpDelete("{id}")] public void Delete(int id) {
}
[HttpPost] public namevalue test(namevalue _info) { return _info; } }
public class namevalue { public String name { get; set; }
public String value { get; set; } } }
|