Search code examples
c#httprequesthttpresponsedotnet-httpclient

HttpClient PostAsync returns 500 when getting token


I am trying to figure out what I can do (logging, things to check) before having to read server logs as I don't want to miss something stupid before requesting that.

Here is my code:

const string URL = "https://SomeURL/api/security/";
string urlParameters = string.Format("grant_type=password&username={0}&password={1}", username, password);
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded");

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded");

var tokenResponse = client.PostAsync("token", content).Result;

I am a little newer to this so I'm not sure what to check next but have tried the same request using postman and get a response with my token so it looks like I am missing something or maybe formatting something incorrectly?


Solution

  • I did not URL encode my parameters, here's the fix (probably a better way of doing it).

    string urlParameters = string.Format("grant_type=password&username={0}&password={1}", Uri.EscapeDataString(username), Uri.EscapeDataString(password));