I have a function that calls a GET request and should return a string.
public async Task<string> GetMyRequestAsync()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this._bearer);
var response = client.GetAsync(this._url).Result;
if (response.IsSuccessStatusCode)
{
var resultString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<string>(resultString);
return result;
}
return null;
}
However, the program stops and returns a NullReferenceException error when I call client.GetAsync(). I keep checking what could be null on the debugger but it just stops before it could reach the if statement. I checked the endpoint on Postman and it works fine.
Just to see if it would work, I replaced the bearer and url variables with hard coded strings and it still failed. What am I doing wrong here?
EDIT: I know what a NullReferenceException is, and what is causing it. I've read the linked duplicate thread, and multiple other questions referring to this problem before I posted. It wasn't helpful in my case so I posted my own question.