目錄web
.Net Core中有兩個集成NSwag的包,分別爲
Swashbuckle
和NSwag
。二者的配置大同小異。這裏以NSwag
爲例。json
新建asp.net core項目,此處略過;
新建apicontroller,並編寫測試代碼;windows
[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 命令安裝:api
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(); }
啓動應用。 轉到:
http://localhost:
http://localhost:
在 Startup.ConfigureServices 方法中,傳遞給 AddSwaggerDocument 方法的配置操做會添加諸如做者、許可證和說明的信息:app
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 顯示版本的信息:
asp.net
若要啓用 XML 註釋,請執行如下步驟:
以windows先使用vs爲例:post
*以上講解知識入門級的,能大致使用起來,能知足通常性需求;測試