When consuming REST Web Service like WebApi based service from Windows Phone you will sometimes have to set the content-type header to some value.
This is for example the case when you want to serialize the body of the POST request like shown below:
public async void PublishToServerAsync(XFile file) { HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(this.ViewData.ServiceUrl); var stream = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(XFile)); ser.WriteObject(stream, file); httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json"); var response = await httpClient.PostAsync(httpClient.BaseAddress, content); } |
This cade will fail InvalidOperationException.
An exception of type 'System.InvalidOperationException' occurred in System.Net.Http.DLL but was not handled in user code
This is because the Content-Type header is not the request header. Content-Type is a content header.
public async void PublishToServerAsync(XFile file) { HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(this.ViewData.ServiceUrl); var stream = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(XFile)); ser.WriteObject(stream, file); StreamContent content = new StreamContent(stream); content.Headers.Add("Content-Type", "application/json"); var response = await httpClient.PostAsync(httpClient.BaseAddress, content); } |
Posted
Nov 26 2013, 04:16 PM
by
Damir Dobric