更新 原来我需要做的就是升级到 .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 年,我认为它会是那个,但在使用它时仍然得到 401。
然后我发现了 .NET Core github 中提出的这个问题,上面写着 it has been resolved .我尝试关注 a code example there但还是不行。
我的代码
这是我目前所做的,我更改了托管在公司网络上的 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;
}
}
如果您有任何想法/建议,请告诉我。
最佳答案
对于 .NET Core 2.1,我使用 HttpClientFactory
在 ConfigureServices(IServiceCollection services)
的 class Startup
中,我有这个名为 HttpClient
的注册:
services.AddHttpClient("myName").ConfigurePrimaryHttpMessageHandler(_ => new HttpClientHandler
{
Credentials = new CredentialCache {
{
new Uri("url"), "NTLM", new NetworkCredential("username", "password", "domain")
}
}
});
在你需要HttpClient
的地方,这样解析就可以了:
var client = _httpClientFactory.CreateClient("myName");
不要忘记在构造函数中注入(inject)工厂。
public class MyClass{
private readonly IHttpClientFactory _httpClientFactory;
public MyClass(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
}
祝你好运!
关于c# - 在 .NET Core 的 Web 请求中使用 NTLM 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53699918/