使用来自.NET 4.5的域凭据调用REST服务HttpClient
问题描述:
我想调用需要.NET 4.5的域身份验证的REST服务。 (使用Visual Studio 2012)使用来自.NET 4.5的域凭据调用REST服务HttpClient
搜索谷歌导致许多人说,HttpClient现在的方式来做到这一点。
但是,据我所知,没有办法模拟或附加凭据到HttpClient。
另外,所有流行的REST库似乎都不兼容.NET 4.5。
超过StackOverflow posts建议使用WebClient作为解决此问题的一种方法,尽管这在.NET 4.5中似乎不再可用。
如果我想使用.NET 4.5客户端的域凭据调用REST服务,最好的方法是什么?
答
.NET 4.5中的HttpClient不支持域身份验证。你需要插入HttpClientHandler与“UseDefaultCredentials”设置为true:
string searchResults = string.Empty;
try
{
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.MaxResponseContentBufferSize = 100000;
string responseString = await client.GetStringAsync(RestServiceUrl);
searchResults = responseString;
}
catch (HttpRequestException e)
{
searchResults = e.Message;
}
另外值得注意的是,如果你正在建设一个Windows 8应用程序,那么你需要启用“企业认证”在包中。 appManifest:
现在看来似乎是复杂的研究HttpClient的,因为它已经经历了漫长的测试周期消失,成为.NET 4.5的一部分,之前发生了很大变化。简单的答案是,这很简单:http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/35e2a7ae-bba0-406a-a10e-f1677dd5a471/ – Andrew 2013-03-17 08:02:33