HttpClient post json data

While I was debugging the Mobile application for login and API connectivity observed issues and Http error codes – 500, 4xx, and did not understand whats went wrong. So I end up writing a simple code snippet for Http client.

First issue: There was problem with header json
Second issue: Issue with Model validation in place bool, i was passing string causing the model validation but due to not proper exception, it was showing 500 internal common error message

StatusCode: 500, ReasonPhrase: ‘Internal Server Error’, Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent

System.NullReferenceException: Object reference not set to an instance of an object.

login.Email = "email@email.com";
login.Password = "password";
login.RememberMe = true;

var json = JsonConvert.SerializeObject(login);
var data = new StringContent(json, Encoding.UTF8, "application/json");

var url = "http://yourwebsite.com/api/account/login";
using var client = new HttpClient();

client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var response = await client.PostAsync(url, data);

string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);

If cookie-based authentication add handler with cookie container

    var cookieContainer = new CookieContainer();

    using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
    using (var client = new HttpClient(handler) { BaseAddress = requestUrl})

As per experience, i have also observed sometime sequence of model and Json serialization causing issues. Ex: if you pass Enum, throw excetion

Leave a Reply

Your email address will not be published.