How to Send x-www-form-urlencoded Data with HttpClient in C#

By FoxLearn 1/9/2025 2:01:52 AM   56
To send x-www-form-urlencoded data in C# using HttpClient, you can follow these steps:
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;

public class MyHttpService
{
    private readonly HttpClient _httpClient;

    // Injecting IHttpClientFactory into the constructor
    public MyHttpService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient();
    }

    public async Task<string> PostFormUrlEncodedData(string url)
    {
        var data = new[]
        {
            new KeyValuePair<string, string>("formfield1", "formvalue1"),
            new KeyValuePair<string, string>("formfield2", "formvalue2"),
            new KeyValuePair<string, string>("formfield3", "formvalue3")
        };

        var content = new FormUrlEncodedContent(data);

        // Perform the POST request
        var response = await _httpClient.PostAsync(url, content);
        
        // Check for success status code
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"{response.StatusCode}: {response.ReasonPhrase}");
        }

        // Read and return the response content as string
        var responseJson = await response.Content.ReadAsStringAsync();
        return responseJson;
    }
}

The FormUrlEncodedContent automatically assigns the Content-Type header to application/x-www-form-urlencoded.

Using IHttpClientFactory ensures that HttpClient instances are reused and not created for each request, which is a best practice for managing HTTP connections.