Calling REST service with domain credentials from

2019-07-17 21:51发布

问题:

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: