【发布时间】:2021-12-17 09:49:10
【问题描述】:
我有以下代码来生成令牌。
如果令牌已经生成,我如何确保重新使用它。该令牌用于后续 API 调用。
using (var client = new HttpClient())
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("username", _user));
postData.Add(new KeyValuePair<string, string>("password", _pwd));
postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
postData.Add(new KeyValuePair<string, string>("client_id", _clientId));
postData.Add(new KeyValuePair<string, string>("client_secret", _clientSecret));
HttpContent content = new FormUrlEncodedContent(postData);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var responseResult = client.PostAsync(_tokenUrl, content).Result;
return responseResult.Content.ReadAsStringAsync().Result;
}
【问题讨论】:
-
这能回答你的问题吗? Setting Authorization Header of HttpClient
-
我想检查一个令牌的有效性。
-
创建另一个
HttpClient实例以进行 API 调用并设置httpClient.DefaultRequestHeaders.Authorization,如我的第一条评论所示。通过该 httpclient 进行的所有后续 API 调用都将包含该令牌。 -
我们需要更多详细信息来指导您找到合适的解决方案。令牌的生命周期是多少?多长时间好用?
-
上述代码每次调用都会获取一个新的token。一旦获得令牌,您选择做什么决定了它是否被重用。你没有表现出来。所以 3600 秒 - 那是 1 小时。所以我要做的是存储令牌和令牌预计到期的日期时间。在每次通话时,我都会检查存储的日期时间。如果在到期时间前 2 分钟,那么我会继续获取新令牌。您最有可能需要将令牌和到期时间存储在某个单例类中。你有依赖注入系统吗?
标签: c# asp.net asp.net-mvc asp.net-web-api