C# GetDiscoveryDocumentAsync失败,IdentityServer4客户端

C# GetDiscoveryDocumentAsync失败,IdentityServer4客户端,c#,identityserver4,dotnet-httpclient,httpclientfactory,C#,Identityserver4,Dotnet Httpclient,Httpclientfactory,我有一个助手类从IdentityServer4获取访问令牌。代码如下: public class ServerTokenHelper { static TokenResponse Token { get; set; } static DateTime ExpiryTime { get; set; } string _host; string _clientId; string _clientSecret; string _clientScope

我有一个助手类从IdentityServer4获取访问令牌。代码如下:

public class ServerTokenHelper
{
    static TokenResponse Token { get; set; }
    static DateTime ExpiryTime { get; set; }

    string  _host;
    string _clientId;
    string _clientSecret;
    string _clientScopes;

    static object ThreadLock = new object();


    static ConcurrentDictionary<string, Tuple<string, string, TokenResponse, DateTime>> userNameCache =
        new ConcurrentDictionary<string, Tuple<string, string, TokenResponse, DateTime>>();
    private static HttpClient _tokenClient = new HttpClient();

    public ServerTokenHelper(string commAddress, string host, string clientId, string clientSecret, string clientScopes)
    {
        _host = host;
        _clientId = clientId;
        _clientSecret = clientSecret;
        _clientScopes = clientScopes;
    }
        public async Task<TokenResponse> GetUserTokenResponseAsync(string userName, string password)
    {
        if (userName != null && userName.Length > 0)
        {
            lock (ThreadLock)
            {
                if (userNameCache.TryGetValue(userName, out var cacheItem))
                {
                    // Since we always cache the result below, we should verify before reusing an entry that the IdentityToken
                    // isn't null because of an error getting it last time!
                    if (cacheItem.Item2 == password && cacheItem.Item3 != null && cacheItem.Item3.IdentityToken != null
                        && cacheItem.Item4 > DateTime.UtcNow)
                    {
                        // System.Diagnostics.Debug.WriteLine($"GetUserTokenResponseAsync({userName}): returning cached value");
                        return cacheItem.Item3;
                    }
                }
            }
        }

        Trace.WriteLine($"GetUserTokenResponseAsync({userName}): new token being retrieved...");

        bool blHttps = false;
        if (_host.ToLower().Contains("https")) blHttps = true;
        var disco = await _tokenClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
        {
            Address = _host,
            Policy = { RequireHttps = blHttps }
        });
        if (disco.IsError)
        {
            Trace.WriteLine($"GetUserTokenResponseAsync({userName}): GetDiscoveryDocumentAsync failed: {disco.Error}");
            return null;
        }
        // request token
        var tokenResponse = await _tokenClient.RequestPasswordTokenAsync(new PasswordTokenRequest
        {
            Address = disco.TokenEndpoint,
            ClientId = _clientId,
            ClientSecret = _clientSecret,
            Scope = _clientScopes,
            UserName = userName,
            Password = password
        });
        if (tokenResponse.IsError)
        {
            Trace.WriteLine($"GetUserTokenResponseAsync({userName}): Could not retrieve token. {tokenResponse.Error} - {tokenResponse.ErrorDescription}");
        }

        lock (ThreadLock)
        {
            userNameCache[userName] = Tuple.Create(userName, password, tokenResponse,
                DateTime.UtcNow.AddSeconds((tokenResponse != null) ? tokenResponse.ExpiresIn - 120 : 0));
        }

        return tokenResponse;
    }

通过这种更改,我们偶尔会出现一些错误。代码功能位于生产服务器中。每小时可能有数千个api调用。以下是错误消息:

GetUserTokenResponseAsync:GetDiscoveryDocumentAsync失败


有人能解释一下这个简单的更改导致了什么问题吗?

对于HttpClient,这一行就是问题所在

private static HttpClient _tokenClient = new HttpClient();
HttpClient不应该被重用/缓存,而是应该在每次使用后对其进行处理,因为您可能会收到各种问题,如DNS或TCP/IP端口耗尽

但更好的是,为什么不将发现文档缓存X分钟?这份文件不会经常改变

见以下文章:

private static HttpClient _tokenClient = new HttpClient();
private static HttpClient _tokenClient = new HttpClient();