asp.net-corehttpclientx-www-form-urlencoded

Passing data in application/x-www-form-urlencoded in HttpClient


data : P1;P2
format : json

Corresponding curl code from POSTMAN

curl --location --request POST 'https://ap-url/id/' \
--header 'content-type: application/x-www-form-urlencoded' \
--data-urlencode 'data=P1;P2' \

How to send the data as x-www-form-urlencoded on HttpClient?


Solution

    1. Use https://curl.olsh.me/ for curl commands to C# code
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api-url/id"))
        {
            var contentList = new List<string>();
            contentList.Add($"data={Uri.EscapeDataString("P1;P2")}");
            contentList.Add($"format={Uri.EscapeDataString("json")}");
            request.Content = new StringContent(string.Join("&", contentList));
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); 
    
            var response = await httpClient.SendAsync(request);
        }
    }