Been elaborating a bit with HttpClient for building a rest client. But I can't figure out, nor find any examples on how to authenticate towards the server. Most likely I will use basic aut, but really any example would be appreciated.
In earlier versions (which has examples online) you did:
HttpClient client = new HttpClient("http://localhost:8080/ProductService/");
client.TransportSettings.Credentials =
new System.Net.NetworkCredential("admin", "admin");
However the TransportSettings
property no longer exists in version 0.3.0.
I believe this is a bit old, but for anyone looking for an updated answer, I used this code when I built my test server:
Or this works too:
The HttpClient library did not make it into .Net 4. However it is available here http://nuget.org/List/Packages/HttpClient. However, authentication is done differently in this version of HttpClient.
or
And be warned, this library is going to get updated next week and there are minor breaking changes!
I tried Duncan's suggestion, but it didn't work in my case. I suspect it was because the server I was integrating with, didn't send a challenge or ask for authentication. It just refused my requests, because I didn't supply an Authorization header.
So I instead did the following:
Notice that the example here only works with Basic authentication.
All these are out of date. The final way to do it is as follows:
For what it is worth, nothing using HttpClientHandler worked, at least not for trying to make an authenticated call to the CouchDB API that requires server admin credentials.
This worked for me:
As outlined in the answer here:
How to use credentials in HttpClient in c#?
I just downloaded 0.3.0 it has indeed be removed. It's now on
HttpClientChannel
If not explicitly specified it uses a default instance of
HttpClientChannel
.UPDATE: this is now invalid for .Net 4.5; see correct answer below: https://stackoverflow.com/a/15034995/58391