Search code examples
c#ihttpclientfactory

Obtaining a token using IHttpclientFactory


I've written the code below in IhttpclientFactory. For some reasons, the code is not returning a token. oauth is returning null. I will appreciate it if someone would kindly have a look and tell me where I've gone wrong. thank you

    private async Task<OAuth>Authenticate()
    {
        //build request
        var request = new HttpRequestMessage(HttpMethod.Post, "/oauth/token");

        request.Content = new StringContent(JsonSerializer.Serialize(new OAuth() {grant_type="client_credentials",client_id="",client_secret=""}));

        request.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/x-www-urlencoded");
                  
        //build client
        var client = _clientFactory.CreateClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/+json"));

        // send the request
        var response = await client.SendAsync(request);

        OAuth oauth = null;

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStringAsync();
            //deserialise

            var oAuth = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuth>(responseStream);
        }
        return oauth;
    }

}

Solution

  • You've got two different OAuth variables 'oauth' and 'oAuth'. C# identifiers are case-sensitive.

    Should be something like

        if (!response.IsSuccessStatusCode)
        {
           throw new InvalidOperationExeption($"OAuth Request Failed With Status code {response.StatusCode}");
        }
        var responseString = await response.Content.ReadAsStringAsync();
        var oAuth = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuth>(responseString);
        return oAuth;