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

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

问题描述

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

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

在 Google 上搜索会找到很多人的链接,他们说 HttpClient 现在是实现此目的的方法.

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

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

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

此外,所有流行的 REST 库似乎都不兼容 .NET 4.5.

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

超过 StackOverflow 帖子已经建议使用 WebClient 作为解决此问题的方法,尽管这在 .NET 4.5 中似乎不再可用.

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

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

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

推荐答案

.NET 4.5 中的 HttpClient 确实支持域身份验证.您需要插入一个UseDefaultCredentials"设置为 true 的 HttpClientHandler:

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;
        }

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

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天全站免登陆