WebClient (legacy) và HttpClient (modern) đều có thể POST dữ liệu. Khuyến nghị dùng HttpClient cho .NET Core / .NET 5+.
Cách 1: WebClient (Legacy - .NET Framework)
using System.Net;
using Newtonsoft.Json;
public class User
{
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public int UserId { get; set; }
}
class Program
{
static void Main()
{
var user = new User { Id = 1, Title = "First Data", Body = "First Body", UserId = 222 };
using (var client = new WebClient())
{
client.BaseAddress = "https://jsonplaceholder.typicode.com";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; MSIE 6.0)";
string json = JsonConvert.SerializeObject(user);
string response = client.UploadString("/posts", json); // POST
var result = JsonConvert.DeserializeObject(response);
Console.WriteLine($"Created: Id={result.Id}, Title={result.Title}");
}
Console.ReadLine();
}
}
Cách 2: HttpClient (Modern - .NET Core / .NET 5+)
using System.Net.Http;
using System.Net.Http.Json; // .NET 5+ built-in
using System.Text.Json; // System.Text.Json
public class User
{
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public int UserId { get; set; }
}
class Program
{
static readonly HttpClient _client = new HttpClient
{
BaseAddress = new Uri("https://jsonplaceholder.typicode.com/"),
Timeout = TimeSpan.FromSeconds(30)
};
static async Task Main()
{
var user = new User { Title = "New Post", Body = "Content", UserId = 1 };
// .NET 5+ built-in JSON (System.Text.Json)
HttpResponseMessage response = await _client.PostAsJsonAsync("posts", user);
response.EnsureSuccessStatusCode();
User created = await response.Content.ReadFromJsonAsync();
Console.WriteLine($"Created: {created.Id} - {created.Title}");
// Hoặc dùng Newtonsoft.Json
// string json = JsonConvert.SerializeObject(user);
// var content = new StringContent(json, Encoding.UTF8, "application/json");
// var response = await _client.PostAsync("posts", content);
}
}
Cách 3: HttpClient với Newtonsoft.Json (Tuỳ chỉnh)
using Newtonsoft.Json;
static async Task PostWithNewtonsoft(HttpClient client, User user)
{
string json = JsonConvert.SerializeObject(user, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("posts", content);
response.EnsureSuccessStatusCode();
string responseJson = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject(responseJson);
}
So sánh WebClient vs HttpClient
| Đặc điểm | WebClient | HttpClient |
|---|---|---|
| Status | Legacy, obsolete | Modern, khuyến nghị |
| Async | Có (Event-based APM) | Native async/await (TAP) |
| Performance | Tạo mới mỗi request | Reuse connection (pooling) |
| Dependency Injection | Khó | Dễ (IHttpClientFactory) |
| JSON Support | Manual | Built-in (PostAsJsonAsync, ReadFromJsonAsync) |
Best Practice với HttpClient
- Dùng
IHttpClientFactory(DI) để quản lý lifetime, tránh socket exhaustion. - Một
HttpClientstatic/singleton cho toàn app. - Set
TimeoutvàBaseAddress. - Luôn
EnsureSuccessStatusCode()hoặc checkIsSuccessStatusCode.