Calling REST service with domain credentials from .NET 4.5 HttpClient

筅森魡賤 提交于 2019-12-24 01:44:10

问题


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?


回答1:


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:



来源:https://stackoverflow.com/questions/15434779/calling-rest-service-with-domain-credentials-from-net-4-5-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!