Update 原来我需要做的就是升级到.NET Core 2.1!感谢大家的解决方案!
我有一个.NET Core 2.0控制台应用程序,需要向使用Windows身份验证(特别是NTLM)的API发出Web请求 . 这是我公司的内部API,我很难成功连接到它,继续获得401 .
My research
我检查了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但仍然无法正常工作 .
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;
}
}
如果您有任何想法/建议,请告诉我 .
1 回答
对于.NET Core 2.1,我使用
HttpClientFactory
实现了此实现在
class Startup
的ConfigureServices(IServiceCollection services)
中,我将此命名为HttpClient
注册:在您需要的位置
HttpClient
就像这样解决它:不要忘记在构造函数中注入工厂 .
祝好运!