Làm việc với API và Web Services trong C# – Phần 15
1. Giới thiệu về API và Web Services
API (Application Programming Interface) là cầu nối giúp các ứng dụng giao tiếp với nhau. Trong C#, bạn có thể làm việc với RESTful API, SOAP API, hoặc xây dựng Web API bằng ASP.NET.
✅ Các tình huống sử dụng API:
- Lấy dữ liệu từ dịch vụ bên ngoài (ví dụ: thời tiết, tỷ giá, bản đồ).
- Tạo API riêng để giao tiếp giữa client và server.
- Gửi và nhận dữ liệu JSON/XML.
📌 Các công nghệ phổ biến:
HttpClientđể gọi API từ C#.ASP.NET Core Web APIđể tạo API riêng.Swaggerđể tạo tài liệu API.
2. Gửi yêu cầu HTTP bằng HttpClient
🔹 HttpClient là thư viện mạnh mẽ để gọi REST API từ C#.
2.1. Cài đặt HttpClient
HttpClient có sẵn trong .NET Core và .NET Framework, không cần cài đặt thêm.
2.2. Gửi yêu cầu GET
💡 Ví dụ: Lấy dữ liệu JSON từ API giả lập.
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string url = "https://jsonplaceholder.typicode.com/posts/1";
using HttpClient client = new HttpClient();
string response = await client.GetStringAsync(url);
Console.WriteLine("✅ Dữ liệu từ API:");
Console.WriteLine(response);
}
}
📌 Giải thích:
GetStringAsync(url)tải dữ liệu từ API.awaitgiúp gọi API bất đồng bộ (không làm đứng chương trình).
2.3. Gửi yêu cầu POST
💡 Ví dụ: Gửi dữ liệu JSON lên server.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string url = "https://jsonplaceholder.typicode.com/posts";
string jsonData = "{ \"title\": \"Hello API\", \"body\": \"Lập trình C#\", \"userId\": 1 }";
using HttpClient client = new HttpClient();
StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine("✅ Phản hồi từ server:");
Console.WriteLine(result);
}
}
📌 Giải thích:
StringContentgiúp gửi dữ liệu JSON.PostAsync(url, content)gửi yêu cầu POST.response.Content.ReadAsStringAsync()lấy phản hồi từ server.
3. Xây dựng Web API với ASP.NET Core
🔹 Nếu bạn muốn tạo API riêng, ASP.NET Core là lựa chọn hàng đầu.
3.1. Cài đặt ASP.NET Core Web API
👉 Mở terminal và chạy lệnh sau để tạo project API:
dotnet new webapi -n MyWebAPI
cd MyWebAPI
dotnet run
📌 Mặc định API chạy tại https://localhost:5001 hoặc http://localhost:5000.
3.2. Tạo Controller API
🔹 Tạo file StudentController.cs trong thư mục Controllers
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
[Route("api/students")]
[ApiController]
public class StudentController : ControllerBase
{
private static List<string> students = new() { "An", "Bình", "Cường" };
[HttpGet]
public IActionResult GetStudents()
{
return Ok(students);
}
[HttpPost]
public IActionResult AddStudent([FromBody] string name)
{
students.Add(name);
return Ok($"✅ Đã thêm sinh viên: {name}");
}
}
📌 Giải thích:
[Route("api/students")]: API truy cập qua/api/students.[HttpGet]: API lấy danh sách sinh viên.[HttpPost]: API thêm sinh viên mới.
3.3. Kiểm thử API với Swagger
Swagger giúp kiểm thử API dễ dàng.
👉 Mở file Program.cs, bật Swagger:
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapControllers();
app.Run();
📌 Chạy lại API (dotnet run) và truy cập https://localhost:5001/swagger để kiểm thử.
4. Gọi API từ C# với HttpClient
💡 Ví dụ: Gọi API vừa tạo từ HttpClient.
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string apiUrl = "https://localhost:5001/api/students";
using HttpClient client = new HttpClient();
string response = await client.GetStringAsync(apiUrl);
Console.WriteLine("✅ Danh sách sinh viên:");
Console.WriteLine(response);
}
}
📌 Nhớ chạy API trước khi gọi từ client.
5. Tổng Kết
✅ HttpClient giúp gọi API RESTful trong C#.
✅ ASP.NET Core Web API giúp tạo API mạnh mẽ.
✅ Swagger giúp kiểm thử API dễ dàng.
✅ API giúp ứng dụng mở rộng và kết nối linh hoạt hơn.
💡 Bài tiếp theo:
👉 Xây dựng ứng dụng desktop với WinForms/WPF trong C# – Phần 16 🚀