0

我在 IhttpclientFactory 中编写了以下代码。由于某些原因,代码没有返回令牌。oauth 返回 null。如果有人愿意看看并告诉我哪里出错了,我将不胜感激。谢谢你

    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;
    }

}
4

1 回答 1

1

您有两个不同的 OAuth 变量“oauth”和“oAuth”。C# 标识符区分大小写。

应该是这样的

    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;
于 2021-03-20T17:41:35.340 回答