.Net Core中有两个集成NSwag的包,分别为 Swashbuckle
和 NSwag
。两者的配置大同小异。这里以 NSwag
为例。
新建asp.net core项目,此处略过;
新建apicontroller,并编写测试代码;
[Route("api/[controller]")] [ApiController] public class UserApiController : ControllerBase { /// <summary> /// 获取用户信息,根据用户id /// </summary> /// <param name="id">用户id</param> /// <returns></returns> [HttpGet("getuser/{id}")] public ActionResult GetUser(int id) { User u = new User { Id=1,Name="Jack"}; return Ok(new { ok = true, data = u }); } /// <summary> /// 添加用户 /// </summary> /// <param name="user">用户信息</param> /// <returns></returns> [HttpPost("postuser")] public ActionResult AddUser([FromBody]User user) { return Ok(new { ok = true, data = user }); } }
public class User { /// <summary> /// 用户id /// </summary> public int Id { get; set; } /// <summary> /// 用户姓名 /// </summary> public string Name { get; set; } }
方式一:通过vs图形界面安装;
方式二:通过nuget 命令安装:
Install-Package NSwag.AspNetCore
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // Register the Swagger services services.AddSwaggerDocument() }
public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); // Register the Swagger generator and the Swagger UI middlewares app.UseOpenApi(); app.UseSwaggerUi3(); app.UseMvc(); }
启动应用。 转到:
/swagger,以查看 Swagger UI。
/swagger/v1/swagger.json,以查看 Swagger 规范。
在 Startup.ConfigureServices 方法中,传递给 AddSwaggerDocument 方法的配置操作会添加诸如作者、许可证和说明的信息:
public void ConfigureServices(IServiceCollection services) { //services.AddControllers(); services.AddControllersWithViews(); services.AddSwaggerDocument(config => { config.PostProcess = document => { document.Info.Version = "v1"; document.Info.Title = "UserManageApp API"; document.Info.Description = "A simple ASP.NET Core web API"; document.Info.TermsOfService = "None"; document.Info.Contact = new NSwag.OpenApiContact { Name = "张三", Email = string.Empty, Url = "https://example.com" }; document.Info.License = new NSwag.OpenApiLicense { Name = "Use under LICX", Url = "https://example.com/license" }; }; }); }
Swagger UI 显示版本的信息:
若要启用 XML 注释,请执行以下步骤:
以windows先使用vs为例:
https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/getting-started-with-nswag?view=aspnetcore-3.0&tabs=visual-studio
*以上讲解知识入门级的,能大体使用起来,能满足一般性需求;