Home > other >  Post from request body with HttpClient
Post from request body with HttpClient

Time:09-08

Trying to consume a REST api using HttpClient. Im required to pass username and password through the body. Below is my code,Its however not posting the data values;

 var data = new Dictionary<string, string>
        { {"username","username"},
         {"password","password"}};
        var jsonData = JsonConvert.SerializeObject(data);
        HttpClient client2 = new HttpClient();
        var requestContent2 = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
        client2.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", access_token);
        HttpResponseMessage response2 = await client2.PostAsync(nitaauthapi, requestContent2);
        HttpContent content2 = response2.Content;
        string result2 = await content2.ReadAsStringAsync();
        JObject jObject2 = JObject.Parse(result2);
        string NONCE = jObject2["NONCE"].Value<string>();

CodePudding user response:

Here, you correctly encode your data as JSON:

var jsonData = JsonConvert.SerializeObject(data);

Afterwards, you ignore your JSON-encoded data and instead send the string "System.Collections.Generic.Dictionary`2[System.String,System.String]" (= the output of data.ToString()) to your API endpoint:

var requestContent2 = new StringContent(data.ToString(), Encoding.UTF8, "application/json");

To fix this, use jsonData in your StringContent instead of data.ToString().


How to avoid such issues in the future: Pay attention to Visual Studio's hints. Visual Studio will highlight jsonData in a light grey color and add three dots underneath to inform you that something might be wrong with it:

code example

Hovering over it will produce a tooltip telling you that the variable's value is unused.

  • Related