更新
我只需要升级到.NET Core 2.1!感谢大家提供的解决方案!
我有一个.NET Core 2.0控制台应用程序,需要向使用Windows身份验证(特别是NTLM)的API发出Web请求。这是我们公司内部的API,我试图成功连接它,但一直得到401错误。
我的研究
我在SO上查阅了以下内容:
- NTLM authentication HttpClient in Core - 去年提出,没有适当的答案表明问题将在以后的.NET Core更新中得到解决。
- Sending HTTP Headers with HTTP Web Request for NTLM Authentication - 这是2009年的内容,不适用于.NET Core。
- How to get HttpClient to pass credentials along with the request? - 这是2012年的内容,我认为这是可行的,但仍然无法成功访问。
然后我发现了这个问题,在.NET Core github上提出,并且它说已经解决了。我尝试遵循那里的代码示例,但仍然无法工作。
我的代码
这是我目前的代码,我更改了Uri,因为它托管在公司网络上,但我希望这足以在本地运行。
public class NTLMProxy
{
private readonly HttpClient _httpClient;
public NTLMProxy()
{
_httpClient = CreateHttpClientWithNTLM();
}
public Task<HttpResponseMessage> GetUsers()
{
var httpRequest = new HttpRequestMessage(HttpMethod.Get, _httpClient.BaseAddress);
return _httpClient.SendAsync(httpRequest);
}
public HttpClient CreateHttpClientWithNTLM()
{
var uri = new Uri("http://ntlmservice.com/services/api/foo");
var credentialsCache = new CredentialCache { { uri, "NTLM", CredentialCache.DefaultNetworkCredentials } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
var httpClient = new HttpClient(handler) { BaseAddress = uri };
httpClient.DefaultRequestHeaders.ConnectionClose = false;
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ServicePointManager.FindServicePoint(uri).ConnectionLeaseTimeout = 120 * 1000; // Close connection after two minutes
return httpClient;
}
}
如果您有任何想法/建议,请让我知道。