有没有一种方法可以重复使用具有多个NTLM凭据的静态c#HTTPClient?

时间:2018-09-26 18:04:55

标签: c# httpclient ntlm

我正在尝试创建一个类来代表用户访问受NTLM保护的终结点。但是,我在使HttpClient保持静态的概念方面苦苦挣扎,以避免在确保用户凭据是线程安全的同时避免占用过多套接字的风险。

是否有一种方法可以设置来自客户端的各个请求的标头中的ntlm auth详细信息,因为我认为这些是线程安全的? 还是有使用我下面未曾考虑过的客户端的替代方法?奖励积分,如果它允许模拟httpclient!

public class SampleClass
{
    private static HttpClient sharedClient;
    private static HttpClient threadSafeClient = new HttpClient();
    private static Uri uri = "http://test.com/ntlmEndpoint";

    public SampleClass(string domain, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler();

        NetworkCredential credential = new NetworkCredential(username, password, domain);
        CredentialCache credentialCache = new CredentialCache();
        credentialCache.Add(uri, "NTLM", credential);
        handler.Credentials = credentialCache;

        //this is real bad as its not thread safe
        sharedClient = new HttpClient(handler);
    }

    //this works however is not thread safe
    public async Task<string> getDataAsyncNotThreadSafe(string key)
    {
        string endpoint = uri + "/" + key;
        HttpResponseMessage response = await sharedClient.GetAsync(endpoint);
        return await response.Content.ReadAsStringAsync(); 
    }


    public static async Task<string> getDataAsyncThreadSafe(string username, string password, string domain, string key)
    {
        string endpoint = uri + "/" + key;
        HttpResponseMessage response;
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, endpoint);

        //add Auth Header here somehow


        request.Headers.Authorization = header;
        response = await threadSafeClient.SendAsync(request);
        return await response.Content.ReadAsStringAsync();
    }
}

0 个答案:

没有答案