首页 > 解决方案 > 令牌过期 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#asp.net-mvc

解决方案


在 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 等待线程完成,因此您永远不需要它。


推荐阅读