How to send HTTP POST request in C# .NET ?

To send an HTTP POST request in C# .NET, you can use several approaches depending on the framework version and requirements. Below is a detailed guide with multiple examples covering different scenarios:

1. Using HttpClient (Modern .NET 5+/Core/Standard)

HttpClient is the recommended asynchronous way to handle HTTP requests in modern .NET.

Example 1: Basic POST with JSON

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class Program
{
    private static readonly HttpClient _client = new HttpClient();

    public static async Task Main()
    {
        var data = new { Name = "John", Age = 30 };
        string json = JsonSerializer.Serialize(data);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        try
        {
            HttpResponseMessage response = await _client.PostAsync(
                "https://api.example.com/users", 
                content
            );

            response.EnsureSuccessStatusCode(); // Throw if non-2xx
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Example 2: POST with Form Data

using System.Collections.Generic;
using System.Net.Http;

var formData = new Dictionary<string, string>
{
    { "username", "johndoe" },
    { "password", "secret" }
};

var content = new FormUrlEncodedContent(formData);
HttpResponseMessage response = await _client.PostAsync(
    "https://api.example.com/login", 
    content
);

2. Using WebClient (Legacy .NET Framework)

Suitable for older .NET Framework apps (synchronous).

Example 3: POST JSON with WebClient

using System.Net;
using System.Text;

var client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string json = "{ \"name\": \"Alice\" }";
string response = client.UploadString(
    "https://api.example.com/data", 
    "POST", 
    json
);
Console.WriteLine(response);

Example 4: POST Form Data with WebClient

var client = new WebClient();
var reqParams = new System.Collections.Specialized.NameValueCollection
{
    { "key1", "value1" },
    { "key2", "value2" }
};
byte[] responseBytes = client.UploadValues(
    "https://api.example.com/form", 
    "POST", 
    reqParams
);
string response = Encoding.UTF8.GetString(responseBytes);

3. Using HttpWebRequest (Low-Level Control)

For fine-grained control over headers and timeouts.

Example 5: POST JSON with HttpWebRequest

using System.IO;
using System.Net;

var request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
request.Method = "POST";
request.ContentType = "application/json";

var data = Encoding.UTF8.GetBytes("{ \"id\": 123 }");
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

try
{
    using var response = (HttpWebResponse)request.GetResponse();
    using var reader = new StreamReader(response.GetResponseStream());
    Console.WriteLine(reader.ReadToEnd());
}
catch (WebException ex)
{
    using var errorResponse = (HttpWebResponse)ex.Response;
    using var reader = new StreamReader(errorResponse.GetResponseStream());
    Console.WriteLine($"Error: {reader.ReadToEnd()}");
}

4. Using IHttpClientFactory (ASP.NET Core Dependency Injection)

Best practice for scalable apps to avoid socket exhaustion.

Example 6: POST with IHttpClientFactory

// In Startup.cs:
services.AddHttpClient();

// In your service class:
public class ApiService
{
    private readonly IHttpClientFactory _clientFactory;

    public ApiService(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public async Task<string> PostDataAsync()
    {
        var client = _clientFactory.CreateClient();
        var data = new { Email = "test@example.com" };
        var content = new StringContent(
            JsonSerializer.Serialize(data), 
            Encoding.UTF8, 
            "application/json"
        );

        var response = await client.PostAsync("https://api.example.com/submit", content);
        return await response.Content.ReadAsStringAsync();
    }
}

5. Advanced Scenarios

Example 7: POST with Headers and Timeout

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer YOUR_TOKEN");
client.Timeout = TimeSpan.FromSeconds(30);

var response = await client.PostAsync(
    "https://api.example.com/secure",
    new StringContent("...")
);

Example 8: Upload a File (Multipart Form)

using var content = new MultipartFormDataContent();
content.Add(new StringContent("John Doe"), "name");
content.Add(new StreamContent(File.OpenRead("report.pdf")), "file", "report.pdf");

var response = await _client.PostAsync(
    "https://api.example.com/upload", 
    content
);

Key Considerations

  1. Async vs. Sync: Prefer async/await for non-blocking requests.
  2. Error Handling: Always check response.IsSuccessStatusCode or use EnsureSuccessStatusCode().
  3. Disposal: Use using blocks for HttpClient, WebClient, or HttpWebResponse to release resources.
  4. JSON Serialization:
  • Newtonsoft.Json: JsonConvert.SerializeObject(data).
  • System.Text.Json: JsonSerializer.Serialize(data) (faster in .NET 5+).
  1. Security: Validate URLs, avoid hardcoding secrets, and use HTTPS.

Summary Table

MethodUse CaseFramework Support
HttpClientModern async apps, .NET 5+/Core/Standard✅ .NET Core, .NET 5+
IHttpClientFactoryScalable apps with dependency injection✅ ASP.NET Core
WebClientLegacy .NET Framework (synchronous)✅ .NET Framework
HttpWebRequestLow-level control (timeouts, headers)✅ All .NET versions

By choosing the right method, you can efficiently send HTTP POST requests in C# while adhering to best practices!

Leave a Reply

Your email address will not be published. Required fields are marked *