-2
  • Passing data from POSTMAN as x-www-form-urlencoded
  • Key and values are as follows:
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?

Dev-lop-er
  • 578
  • 1
  • 7
  • 16
  • Duplicate of [Making a cURL call in C#](https://stackoverflow.com/questions/7929013/making-a-curl-call-in-c-sharp) – TylerH Jun 30 '20 at 14:13

2 Answers2

2
  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);
    }
}
Dev-lop-er
  • 578
  • 1
  • 7
  • 16
0

The best Pattern is to set a dictionary and send this dictionary data in the post method

var client = _clientFactory.CreateClient("mobile-server");

                var data = new[]
                {
                    new KeyValuePair<string, string>("grant_type", "client_credentials"),
                    new KeyValuePair<string, string>("client_id",
                        _configuration.GetValue<string>("MobileTop:ClientId")),
                    new KeyValuePair<string, string>("client_secret",
                        _configuration.GetValue<string>("MobileTop:ClientSecret")),
                };
                var response =
                    await client.PostAsync("api/v2/connect/token", new FormUrlEncodedContent(data));