2012-10-25 23 views
2

我從Windows應用商店(Windows Metro應用)調用RESTful Web服務(在Azure中託管)。這是服務的定義:從Windows應用商店使用JSON的WCF RESTful POST

[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); 

從Windows應用商店的應用程序,調用的時候,我收到請求錯誤發佈後(它甚至沒有打到我放在PostDummyData斷點我曾嘗試以下方法:

使用的StringContent對象

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)) 
    { 
     // ... 
    } 
} 

使用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)) 
    { 
     // ... 
    } 
} 

我想這可能是有問題的內容類型標題(最後檢查它設置爲純文本,但我找不到方法來更改它)。

雖然HTTP GET方法工作正常。如果有人能指出我正確的方向,我將不勝感激。謝謝!

回答

2

您應該設置內容類型的StringContent對象:

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

或直接:

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

不能相信我錯過了構造出來。非常感謝!現在它工作了! –