我正在尝试在.NET Core 2.1 Web-API中进行模拟。所以这个Web-API使用HttpClient调用另一个Web-API,我需要调用第一个的用户也是执行第二个的用户。使用此调用的完整框架运行的另一个Web-API也可以使用相同的方案:
((WindowsIdentity)_httpContextAccessor.HttpContext.User.Identity).Impersonate()
由于Impersonate()
在.NET Core 2.1中不可用,我使用WindowsIdentity.RunImpersonated
搜索了一些示例并尝试了与此类似的不同版本的代码:
WindowsIdentity identity = (WindowsIdentity)m_contextAccessor.HttpContext.User.Identity;
HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
await WindowsIdentity.RunImpersonated(identity.AccessToken, async () =>
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
var response = await client.SendAsync(request);
});
这会在client.SendAsync
引发错误,错误消息是这样的:
在此调用仍在处理时,调用了WSALookupServiceEnd。该调用已被取消---> System.Net.Http.HttpRequestException
堆栈跟踪的开始:
在System.Net.Http.ConnectHelper.ConnectAsync(String host,Int32 port,CancellationToken cancellationToken)---内部异常堆栈跟踪结束---在System.Net.Http.ConnectHelper.ConnectAsync(String host,Int32 port,CancellationToken)在System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage请求,CancellationToken cancellationToken)的System.Threading.Tasks.ValueTask`1.get_Result()处取消。
有没有其他人看到这个错误或有任何洞察力如何解决这个问题?我尝试使用RunImpersonated
用户调用HttpContext
的不同版本的代码,所有这些都会导致相同的错误。
感谢您的任何意见
从.NET Core 2.1开始,SocketsHttpHandler类提供了更高级别的HTTP网络类(如HttpClient)使用的实现。尝试disable这个功能,看看异常是否消失。
即使这个错误超级模糊,我也很确定这个问题与服务器拒绝连接到端点有关,或者它无法找到端点。我的问题是网络服务器看不到端点 - 而且仅供参考,不要使用“localhost:xxxx”指向本地端口。而是在配置中使用服务器完整IP地址。 localhost并不总是在本地DNS中解析。
TLDR:确保您的Web服务器可以使用权限ping端点服务器和端口。
await WindowsIdentity.RunImpersonated(identity.AccessToken, async () =>
{
//this should give you the impersonated user
var impersonatedUser = WindowsIdentity.GetCurrent().Name;
var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
var request = new HttpRequestMessage(HttpMethod.Get, url);
var response = await client.SendAsync(request);
});