前言
.Net Core中有两个集成NSwag的包,分别为Swashbuckle和NSwag。两者的配置大同小异。这里以NSwag为例。
一、前期准备
1、初始化asp.net core 测试项目
新建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; } }
2、使用nuget安装 NSwag.AspNetCore
方式一:通过vs图形界面安装;
方式二:通过nuget 命令安装:
Install-Package NSwag.AspNetCore
二、配置Swagger
1、添加并配置 Swagger 中间件
在应用的Startup类中的ConfigureServices 方法中,注册所需的 Swagger 服务:
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // Register the Swagger services services.AddSwaggerDocument() }
在 Startup类中的Configure 方法中,启用中间件为生成的 Swagger 规范和 Swagger UI 提供服务:
public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); // Register the Swagger generator and the Swagger UI middlewares app.UseOpenApi(); app.UseSwaggerUi3(); app.UseMvc(); }
启动应用。 转到:
http://localhost:/swagger,以查看 Swagger UI。
http://localhost:/swagger/v1/swagger.json,以查看 Swagger 规范。
2、自定义 API 文档
API 信息和说明
在 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" }; }; }); }