c# - 令牌过期 asp net
问题描述
我正在使用以下方法从 asp 网络服务器获取令牌。
public async static Task<bool> GetToken(string username, string password)
{
var token = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
});
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromMilliseconds(20000);
var response = await client.PostAsync(ServerTokenString, token);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
var tokens = content.Split('"');
AccessToken = tokens[3];
TokenType = tokens[7];
return true;
}
return false;
}
}
然后我将令牌和令牌类型保存在字符串中。然后我使用这个令牌来提出我的请求。但是,如果令牌将过期怎么办?我需要重新发送用户名和密码吗?或者如果客户已经登录并且他的令牌已过期,还有更简单的方法?
解决方案
在 C# 中,一个函数可以有多种“风味”——取决于发送的参数的类型和数量,它将调用“具有那种风味”。当我们查看文档时,PostAsync
我们可以看到以下“口味”。(https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.postasync?view=netframework-4.7.2)
PostAsync(Uri, HttpContent, CancellationToken)
发送带有取消令牌的 POST 请求作为异步操作。
PostAsync(String, HttpContent, CancellationToken)
发送带有取消令牌的 POST 请求作为异步操作。
PostAsync(String, HttpContent)
将 POST 请求作为异步操作发送到指定的 Uri。
PostAsync(Uri, HttpContent)
将 POST 请求作为异步操作发送到指定的 Uri。
如果我们仔细查看这些,我们可以看到前 2 个有 3 个参数,并且两者中的第 3 个参数都命名为“CancellationToken”。(您可以阅读文档的其余部分以了解它们的作用。)
接下来的两个有 2 个没有标记的参数。
在您的通话中,您将传递给如下变量
var response = await client.PostAsync(ServerTokenString, token);
由于您传递了两个参数,因此您将调用上面列表中的第 3 或第 4 个版本。这意味着它们不是令牌——(即使名称中有“令牌”)。
您可以像这样更改您的代码:(改编自https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=netframework-4.7.2)
// Define the cancellation token.
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken CToken = source.Token;
var response = await client.PostAsync(ServerTokenString, token, CToken);
然而,这并没有什么好处。由于您使用await
的是 PostAsync,因此将在有时间使用 CancellationToken 之前完成。
仅当进程在另一个线程上运行时才使用 CancellationToken - 使用 await 等待线程完成,因此您永远不需要它。
推荐阅读
- python - 如何修复“xcor() 缺少 1 个必需的位置参数:Python 中的‘self’错误
- javascript - 表单第二部分中未定义的对象
- python - 有一种方法可以在 VS Code 上启用一条视觉线来显示 PEP8 的限制?
- zurb-foundation - 如何使显示高度小于移动设备上的视口?
- php - MySQL PDO dbname 在 MySQL 升级后停止工作
- vba - 如何添加条件以检查主题行是否不包含某些文本并且收件人是否在组织之外?
- redux - 应用程序在首次运行时无法加载。(不能将 undefined 或 null 转换为对象)
- docker - 我的应用程序在使用 docker-compose up 时无法发现 mongodb,链接不起作用?
- css - 如何修复悬停时背景图像的 CSS 过渡?
- google-cloud-shell - 无法“esc”vi 编辑器