从.NET 4.5 HttpClient使用域凭据调用REST服务 [英] Calling REST service with domain credentials from .NET 4.5 HttpClient

查看:143
本文介绍了从.NET 4.5 HttpClient使用域凭据调用REST服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个需要从.NET 4.5进行域身份验证的REST服务。 (使用Visual Studio 2012



搜索Google会导致很多人称HttpClient现在是实现此目的的链接。



但是,据我所知,无法模拟或将凭据附加到HttpClient。



所有流行的REST库似乎都尚未与.NET 4.5兼容。



建议使用WebClient作为解决此问题的一种方法。 p>

如果我想从.NET 4.5客户端使用域凭据调用REST服务,什么是最好的方法?

HttpClient不支持域身份验证。您需要插入 UseDefaultCredentials设置设为true的HttpClientHandler:

 字符串searchResults = string.Empty; 

试试
{
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);

client.MaxResponseContentBufferSize = 100000;
string responseString =等待客户端.GetStringAsync(RestServiceUrl);

searchResults = responseString;
}
catch(HttpRequestException e)
{
searchResults = e.Message;
}

另外值得注意的是,如果您要构建Windows 8应用程序,那么您需要在Package.appManifest中启用企业身份验证:




I want to call a REST service that requires domain authentication from .NET 4.5. (Using Visual Studio 2012)

Searching Google leads to lots of links of people saying that HttpClient is now the way to do this.

However as far as I can tell there is no way to impersonate or attach credentials to HttpClient.

In addition, all the popular REST libraries seem to not be compatible with .NET 4.5 yet.

Over StackOverflow posts have suggested WebClient as a way around this, although this seems no longer available in .NET 4.5.

If I want to call a REST service with domain credentials from a .NET 4.5 client, what is the best method?

解决方案

HttpClient in .NET 4.5 does support domain authentication. You need to insert a HttpClientHandler with the 'UseDefaultCredentials' setting set to 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;
        }

Also it is worth noting that if you are building a Windows 8 application then you need to enable 'Enterprise Authentication' in the Package.appManifest:

这篇关于从.NET 4.5 HttpClient使用域凭据调用REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆