NSwag เป็นเครื่องที่มีหลายฟังก์ชัน สามารถอ่านเพิ่มใน GitHub และ Wiki โพสนี้จะแสดงเฉพาะวิธี Generate โค้ดสำหรับเชื่อม API ของ ASP.NET Core ด้วย NSwag.MSBuild เท่านั้น โดยจะ Generate โค้ดออกมา 2 ชุด ได้แก่ TypeScript (fetch) และ C# (HttpClient)
สามารถโหลดโค้ดในตัวอย่างจากลิงก์นี้ MyApi
สร้างโปรเจคและติดตั้ง Package
dotnet new webapi --output src/MyApi
dotnet add src/MyApi/MyApi.csproj package NSwag.MSBuild
เขียน API
ประกาศ StudentController โดยมีฟังก์ชันเดียวคือ Add
สามารถเรียกจาก Client ผ่าน Http post (https://localhost:5001/api/student/add
)
using System;
using Microsoft.AspNetCore.Mvc;namespace MyApi {
public class Student {
public string Id { set; get; }
public string Name { set; get; }
public float Gpa { set; get; }
} [Route("api/[controller]/[action]")]
[ApiController]
public class StudentController : ControllerBase { [HttpPost]
public ActionResult<Student> Add(Student student) {
student.Id = Guid.NewGuid().ToString("N");
return student;
}
}
}
เพิ่ม Build Target ในไฟล์ MyApi.cspoj
เพิ่ม Target ชื่อ NSwag สังเกตว่าจะมีคำสั่ง Exec NSwagExe อยู่ด้วย ทำให้ทุกครั้งที่ Build NSwag จะ Generate โค้ดสำหรับเชื่อม API ออกมาเสมอ
<Target Name="NSwag" AfterTargets="Build">
<Copy SourceFiles="@(Reference)"
DestinationFolder="$(OutDir)References" />
<Exec Command="$(NSwagExe_Core21) run /variables:OutputPath=$(OutputPath)" />
<RemoveDir Directories="$(OutDir)References" />
</Target>
เพิ่มไฟล์ nswag.json
โปรแกรม NSwagExe ใน Target NSwag จะอ่าน Config ในไฟล์ nswag.json (เก็บที่เดียวกับ MyApi.csproj) โดยต้องระบุไฟล์ Input (assemblyPath) และ Output (codeGenerators)
{
"swaggerGenerator": {
"aspNetCoreToSwagger": {
"assemblyPaths": [
"$(OutputPath)/MyApi.dll"
]
}
},
"codeGenerators": {
"swaggerToTypeScriptClient": {
"className": "{controller}Client",
"typeScriptVersion": 1.8,
"template": "Fetch",
"output": "../../client/generated/MyApiClient.ts"
},
"swaggerToCSharpClient": {
"namespace": "MyClient",
"className": "{controller}Client",
"output": "../../client/generated/MyApiClient.cs"
}
}
}
จากตัวอย่าง มีการกำหนดให้ NSwag อ่านข้อมูลจากไฟล์ MyApi.dll
จากนั้นโปรแกรมจะสแกนหา API และ Generate โค้ดสำหรับเชื่อม API ออกมา 2 ชุด คือ TypeScript (swaggerToTypeScriptClient) และ C# (swaggerToCSharpClient)โดยโปรแกรมวางโค้ดที่ได้ในไฟล์ output
Build โปรเจค
dotnet build src/MyApi/MyApi.csproj
หลังจาก Build จะได้ MyApi.dll และไฟล์ที่สร้างจาก NSwag อีกสองไฟล์ คือ MyClientApi.ts และ MyClientApi.cs สามารถนำไฟล์ที่ได้ สำหรับเชื่อมต่อ API ได้เลย
ตัวอย่างการนำ StudentClient ไปใช้ในโปรเจค C#
using MyClient;class Program {
static async Task Main(string[] args) {
var client = new StudentClient("https://localhost:5001");
var student = await client.AddAsync(
new Student { Name = "A", Gpa = 4.0 }); Console.WriteLine(student.Id);
}
}