文章

第18天:建立 Web API

課程簡介

今天,我們將學習如何使用 ASP.NET Core 建立一個 Web API。Web API 是一種允許應用程式之間透過 HTTP 進行通訊的方式。透過 ASP.NET Core,我們可以建立一個輕量、強大的 API,來處理 CRUD 操作和其他業務邏輯。


學習目標

  • 了解什麼是 Web API 及其用途
  • 學習如何使用 ASP.NET Core 建立 Web API
  • 掌握如何設置 API 路由和控制器
  • 學會透過 HTTP 請求進行 CRUD 操作

課程內容

1. Web API 簡介

Web API 是一個基於 HTTP 協定的服務,通常用於讓應用程式之間進行通訊。ASP.NET Core 提供了內建的支援來建立 RESTful API。使用 Web API,您可以讓前端應用程式或其他服務與您的後端伺服器進行資料交換。


2. 建立 ASP.NET Core Web API 專案

首先,我們需要建立一個新的 ASP.NET Core Web API 專案。使用以下指令來創建專案:

1
2
dotnet new webapi -n MyWebAPI
cd MyWebAPI

這將會創建一個名為 MyWebAPI 的專案,其中包含基本的 Web API 結構。


3. 設置控制器(Controller)

在 ASP.NET Core 中,控制器 是處理 HTTP 請求的主要部分。控制器是 C# 類別,負責接收請求、處理資料並返回回應。我們可以通過控制器來實現 API 的 CRUD 操作。

新增一個學生控制器:

首先,在 Controllers 資料夾下新增一個名為 StudentsController.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
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace MyWebAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class StudentsController : ControllerBase
    {
        private static List<Student> students = new List<Student>
        {
            new Student { Id = 1, Name = "Alice", Age = 22 },
            new Student { Id = 2, Name = "Bob", Age = 20 }
        };

        // GET: api/students
        [HttpGet]
        public IEnumerable<Student> GetStudents()
        {
            return students;
        }

        // GET: api/students/1
        [HttpGet("{id}")]
        public ActionResult<Student> GetStudent(int id)
        {
            var student = students.Find(s => s.Id == id);
            if (student == null)
            {
                return NotFound();
            }
            return student;
        }

        // POST: api/students
        [HttpPost]
        public ActionResult<Student> PostStudent(Student student)
        {
            students.Add(student);
            return CreatedAtAction(nameof(GetStudent), new { id = student.Id }, student);
        }

        // PUT: api/students/1
        [HttpPut("{id}")]
        public IActionResult PutStudent(int id, Student updatedStudent)
        {
            var student = students.Find(s => s.Id == id);
            if (student == null)
            {
                return NotFound();
            }

            student.Name = updatedStudent.Name;
            student.Age = updatedStudent.Age;

            return NoContent();
        }

        // DELETE: api/students/1
        [HttpDelete("{id}")]
        public IActionResult DeleteStudent(int id)
        {
            var student = students.Find(s => s.Id == id);
            if (student == null)
            {
                return NotFound();
            }

            students.Remove(student);
            return NoContent();
        }
    }
}

4. 模型(Model)

在 ASP.NET Core Web API 中,我們通常會為資料創建一個模型類別來定義結構。在 Models 資料夾下新增 Student.cs 檔案,定義學生類別:

1
2
3
4
5
6
7
8
9
namespace MyWebAPI
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Student 類別將用來表示學生的資料結構,我們會在控制器中用到它來存儲學生的資訊。


5. 路由與動作方法

每個控制器中的 動作方法 都對應到不同的 HTTP 動作(GET、POST、PUT、DELETE)。例如:

  • GET:讀取資料(如 GetStudents()GetStudent(int id)
  • POST:新增資料(如 PostStudent(Student student)
  • PUT:更新資料(如 PutStudent(int id, Student updatedStudent)
  • DELETE:刪除資料(如 DeleteStudent(int id)

這些方法會根據 HTTP 請求來執行相應的操作。


6. 測試 Web API

我們可以使用 PostmancURL 來測試 API,或者使用瀏覽器進行簡單的 GET 請求。

使用 cURL 測試:

  1. GET 所有學生
1
curl -X GET http://localhost:5000/api/students
  1. GET 單個學生
1
curl -X GET http://localhost:5000/api/students/1
  1. POST 新學生
1
curl -X POST http://localhost:5000/api/students -H "Content-Type: application/json" -d "{\"id\": 3, \"name\": \"Charlie\", \"age\": 23}"
  1. PUT 更新學生
1
curl -X PUT http://localhost:5000/api/students/1 -H "Content-Type: application/json" -d "{\"id\": 1, \"name\": \"Alice Updated\", \"age\": 23}"
  1. DELETE 刪除學生
1
curl -X DELETE http://localhost:5000/api/students/1

7. 測試 API(Swagger)

ASP.NET Core Web API 預設支援 Swagger,這是一個互動式的 API 文件工具,可以讓您通過圖形介面測試 API。

啟用 Swagger:

  1. Startup.csProgram.cs 中找到並啟用 Swagger:
1
2
3
4
5
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
  1. 執行應用程式後,打開瀏覽器,輸入 http://localhost:5000/swagger,就能看到 Swagger 提供的 API 測試介面。

教學重點

  • 瞭解如何建立 ASP.NET Core Web API 專案。
  • 使用控制器實現 API 的 CRUD 操作。
  • 使用 Postman 或 cURL 測試 API 請求。
  • 使用 Swagger 提供 API 文件與測試功能。

在下一節中,我們將學習如何在 Web API 中實作 身份驗證與授權

本文章以 CC BY 4.0 授權