使用 IHttpclientFactory 获取令牌
Obtaining a token using IHttpclientFactory
我已经在 IhttpclientFactory 中编写了以下代码。由于某些原因,代码未返回令牌。 oauth 返回空值。
如果有人愿意看一下并告诉我哪里出了问题,我将不胜感激。谢谢
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;
}
}
您有两个不同的 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;
我已经在 IhttpclientFactory 中编写了以下代码。由于某些原因,代码未返回令牌。 oauth 返回空值。 如果有人愿意看一下并告诉我哪里出了问题,我将不胜感激。谢谢
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;
}
}
您有两个不同的 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;