Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

POST dữ liệu lên URL với WebClient trong C#

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ểmWebClientHttpClient
StatusLegacy, obsoleteModern, khuyến nghị
AsyncCó (Event-based APM)Native async/await (TAP)
PerformanceTạo mới mỗi requestReuse connection (pooling)
Dependency InjectionKhóDễ (IHttpClientFactory)
JSON SupportManualBuilt-in (PostAsJsonAsync, ReadFromJsonAsync)

Best Practice với HttpClient

  • Dùng IHttpClientFactory (DI) để quản lý lifetime, tránh socket exhaustion.
  • Một HttpClient static/singleton cho toàn app.
  • Set Timeout và BaseAddress.
  • Luôn EnsureSuccessStatusCode() hoặc check IsSuccessStatusCode.