Tags: , | Categories: REST, WCF Posted by AlexanderZeitler on 3/19/2011 2:52 PM | Comments (0)

Recently I posted how to use ASP.NET Forms authentication with the new WCF Web APIs (german version).

In this posting I have been using the classic HttpWebRequest / HttpWebResponse.

If you take a look into the WCF Web APIs source code, you’ll find a new Version of the HttpClient which is optimized to work with the new APIs.

I modified my sample from my above Posting to make the client use the new HttpClient instead of the old stuff:

CookieContainer cookieContainer = new CookieContainer();
using (HttpClient client = new HttpClient("http://localhost:44857/")) {
	HttpClientChannel clientChannel = new HttpClientChannel();
	clientChannel.CookieContainer = cookieContainer;
	client.Channel = clientChannel;
	HttpContent loginData = new FormUrlEncodedContent(
		new List<KeyValuePair<string, string>>
			{
				new KeyValuePair<string, string>("Username", "foo"),
				new KeyValuePair<string, string>("Password", "bar")
			}
		);
	client.Post("login", loginData);
}

string result = string.Empty;
using (HttpClient client = new HttpClient("http://localhost:44857/contact/")) {
	HttpClientChannel clientChannel = new HttpClientChannel();
	clientChannel.CookieContainer = cookieContainer;
	client.Channel = clientChannel;
	client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
	HttpResponseMessage response = client.Get("1");
	result = response.Content.ReadAsString();
}

JavaScriptSerializer jsonDeserializer = new JavaScriptSerializer();
ContactDto contact = jsonDeserializer.Deserialize<ContactDto>(result);
Console.WriteLine(contact.Name);
Console.ReadLine();

RESTful clients straight forward now ;-)

Download the new version here: WcfHttpMvcAuth.zip (9.62 mb)

DotNetKicks-DE Image
Comments are closed