Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Post from request body with HttpClient

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>();

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading