VT Chiew
VT Chiew

Reputation: 703

WCF RESTful POST using JSON, from Windows Store App

I am calling a RESTful web service (hosted in Azure) from my Windows Store App (Windows Metro App). This is the Service definition:

[OperationContract]
[WebInvoke(UriTemplate="/Test/PostData", 
    RequestFormat= WebMessageFormat.Json, 
    ResponseFormat= WebMessageFormat.Json, Method="POST", 
    BodyStyle=WebMessageBodyStyle.WrappedRequest)]
string PostDummyData(string dummy_id, string dummy_content, int dummy_int);

From the Windows Store Apps, when calling, I am getting Request Error after posting (it did not even hit the breakpoint I placed in PostDummyData. I have tried the following methods:

Using a StringContent object

using (var client = new HttpClient())
{
  JsonObject postItem = new JsonObject();
  postItem.Add("dummy_id", JsonValue.CreateStringValue("Dummy ID 123"));
  postItem.Add("dummy_content", JsonValue.CreateStringValue("~~~Some dummy content~~~"));
  postItem.Add("dummy_int", JsonValue.CreateNumberValue(1444));

  StringContent content = new StringContent(postItem.Stringify());
  using (var resp = await client.PostAsync(ConnectUrl.Text, content))
    {
        // ...
    }
}

Using a HttpRequestMessage

using (var client = new HttpClient())
{
  JsonObject postItem = new JsonObject();
  postItem.Add("dummy_id", JsonValue.CreateStringValue("Dummy ID 123"));
  postItem.Add("dummy_content", JsonValue.CreateStringValue("~~~Some dummy content~~~"));
  postItem.Add("dummy_int", JsonValue.CreateNumberValue(1444));

  StringContent content = new StringContent(postItem.Stringify());
  HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, ConnectUrl.Text);
  msg.Content = content;
  msg.Headers.TransferEncodingChunked = true;

  using (var resp = await client.SendAsync(msg))
    {
        // ...
    }
}

I'd figured that it may be the content-type header that is having problem (last checked it was set to plain text, but I can't find a way to change it).

The HTTP GET methods are all working fine though. Would appreciate if somebody can point me to a correct direction. Thanks!

Upvotes: 2

Views: 1722

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87228

You should set the content-type in the StringContent object:

StringContent content = new StringContent(postItem.Stringify());
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/json");

or directly in the constructor:

StringContent content = new StringContent(postItem.Stringify(),
    Encoding.UTF8, "text/json");

Upvotes: 2

Related Questions