[英]Calling rest api on localhost using HttpClient causing 401 Unauthorized, IIS 8.5
I've just discovered a strange behavior, and I am wondering if someone has an explanation to why my code behaves like this. 我刚刚发现了一个奇怪的行为,并且我想知道是否有人对我的代码为何如此表现有一个解释。
My scenario is this: I have two rest api created in c#, lets call them CoreApi and FrontApi. 我的情况是这样的:我在c#中创建了两个rest api,将它们称为CoreApi和FrontApi。 Both apis have separate sites and appPools on the same server, and both appPools are running as NetworkService. 两种api在同一服务器上都有单独的站点和appPool,而两个appPool都作为NetworkService运行。 FrontApi uses HttpClient to call CoreApi. FrontApi使用HttpClient调用CoreApi。 I trigger the call by calling FrontApi's ValuesController, which in turn calls CoreApi. 我通过调用FrontApi的ValuesController触发了调用,该控制器依次调用CoreApi。 CoreApi has enabled Windows Authentication, while FrontApi has anonymous authentication. CoreApi已启用Windows身份验证,而FrontApi具有匿名身份验证。
If I host FrontApi on my development machine it all works fine, but when cohosting on the same server using the full URL causes 401.0 Unauthorized when FrontApi calls CoreApi. 如果我在开发机器上托管FrontApi,则一切正常,但是当FrontApi调用CoreApi时,使用完整URL在同一服务器上共同托管会导致401.0未经授权。 When using " http://localhost/api/values " from FrontApi it works fine. 从FrontApi使用“ http:// localhost / api / values ”时,它可以正常工作。
Any thoughts? 有什么想法吗?
HttpClientHandler authHandler = new HttpClientHandler()
{
Credentials = CredentialCache.DefaultNetworkCredentials
};
using (HttpClient confClient = new HttpClient(authHandler))
{
HttpResponseMessage message = await confClient.GetAsync("http://mysite.acme.com/api/values");
if (message.IsSuccessStatusCode)
{
result = await message.Content.ReadAsStringAsync();
}
else
result = message.StatusCode.ToString();
}
The CredentialCache.DefaultNetworkCredentials property returns the credentials that the FrontApi IIS application pool is running under. CredentialCache.DefaultNetworkCredentials属性返回运行FrontApi IIS应用程序池的凭据。 The CoreApi doesn't know how to authenticate FrontApi's ApplicationPoolIdentity, but should be able to authenticate NetworkService. CoreApi不知道如何认证FrontApi的ApplicationPoolIdentity,但应该能够认证NetworkService。
If you change the app pool identity from ApplicationPoolIdentity to NetworkService, that should fix your 401 response from CoreApi. 如果将应用程序池标识从ApplicationPoolIdentity更改为NetworkService,则应该可以解决来自CoreApi的401响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.