Update事实证明,我所需要做的就是升级到 .NET Core 2.1!感谢大家的解决方案!
我有一个 .NET Core 2.0 控制台应用程序,需要向使用 Windows 身份验证(特别是 NTLM)的 API 发出 Web 请求。这是我公司的一个内部 API,我很难成功连接到它,不断收到 401 错误。
我的研究
我查看了SO:
-
Core 中的 NTLM 身份验证 HttpClient https://stackoverflow.com/questions/47822842/ntlm-authentication-httpclient-in-core- 去年提出,但没有给出正确的答案,表明该问题将在以后的 .NET Core 更新中得到解决。
-
使用 HTTP Web 请求发送 HTTP 标头以进行 NTLM 身份验证 https://stackoverflow.com/questions/1520703/sending-http-headers-with-http-web-request-for-ntlm-authentication- 这是 2009 年的事情,似乎与 .NET Core 无关。
-
如何让 HttpClient 将凭据与请求一起传递? https://stackoverflow.com/questions/12212116/how-to-get-httpclient-to-pass-credentials-along-with-the-request/12675503#12675503- 这是2012年的事,本以为会是那个,但使用时仍然得到401。
然后我发现这个问题是在 .NET Core github 中提出的,它说已经解决了 https://github.com/dotnet/corefx/issues/25988。我尝试以下那里有一个代码示例 https://github.com/dotnet/corefx/issues/25988#issuecomment-401129910但还是没用。
My code
这是我到目前为止所拥有的,我更改了 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
In ConfigureServices(IServiceCollection services)
in the 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");
不要忘记在构造函数中注入工厂。
public class MyClass{
private readonly IHttpClientFactory _httpClientFactory;
public MyClass(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
}
祝你好运!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)