Tags: , , | Categories: REST, WCF Posted by AlexanderZeitler on 3/21/2011 1:48 PM | Comments (1)

If you need to POST Json data to your REST service, you can do this pretty straight forward using the HttpClient from the WCF Web APIs:

public CustomerDto Add(CustomerDto customerDto) {
	using(HttpClient httpClient = new HttpClient(_baseAddress)) {
		CustomerDto newCustomer = null;
		httpClient.DefaultRequestHeaders.Accept.Add(_json);
		JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
		byte[] customerBytes = Encoding.UTF8.GetBytes(jsonSerializer.Serialize(customerDto));
		using (MemoryStream stream = new MemoryStream(customerBytes)) {
			StreamContent customer = new StreamContent(stream);
			customer.Headers.ContentType = _json;
				using (HttpResponseMessage response = httpClient.Post("", customer)) {
				newCustomer = jsonSerializer.Deserialize<CustomerDto>(response.Content.ReadAsString());
			}
		}
		return newCustomer;
	}
}

where _json is

_json = new MediaTypeWithQualityHeaderValue("application/json");

The code applies to the WCF Web APIs Preview 3.

Update: You know what? It's even simpler using the new HttpContentExtensions and JsonContentExtensions:

public CustomerDto Add(CustomerDto customerDto) {
	using(HttpClient httpClient = new HttpClient(_baseAddress)) {
		CustomerDto newCustomer = null;
		httpClient.DefaultRequestHeaders.Accept.Add(_json);
		StreamContent customer = 
			customerDto.ToContentUsingDataContractJsonSerializer() as StreamContent;
			customer.Headers.ContentType = _json;
				using (HttpResponseMessage response = httpClient.Post("", customer)) {
				newCustomer = response.Content.ReadAsObject<CustomerDto>();
			}
		}
		return newCustomer;
	}

In case you're missing the Microsoft.Http.Extensions.dll: you need to fix the build output path inside the Microsoft.Net.Http.Extensions project to point to the common build directory.

Thanks to Glenn Block for pointing me to the Extensions.

DotNetKicks-DE Image

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Comments are closed