Search code examples
c#web-servicesdotnet-httpclient

How can I Post parameter in httpClient where in Postman use param


I want to post my parameter with HttpClient. What is the Content in httpclient request body? I wrote it int the body part and when I run the project I get error:

enter image description here

My code is:

string baseAddress = "https://WebServiceAddress";
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
HttpRequestMessage bodyRequest = new HttpRequestMessage(HttpMethod.Post, baseAddress)

bodyRequest.Content = new StringContent(JsonConvert.SerializeObject(Prescriptionrequest), Encoding.UTF8, "application/json");

var responseApi = Client.PostAsync(baseAddress, bodyRequest.Content, new System.Threading.CancellationToken(false));

what should be the format of bodyRequest.Content?


Solution

  • Use this code:

    HttpClient client = new HttpClient();
    var dictionary = new Dictionary<string, string> 
    {    
        { "parameter0", "value0" },    
        { "parameter1", "value1" }
    };    
    var content = new FormUrlEncodedContent(dictionary);    
    var response = await client.PostAsync("https://WebServiceAddress", content);    
    var responseString = await response.Content.ReadAsStringAsync();