2

我正在从我的 Windows Store 应用程序(Windows Metro 应用程序)调用 RESTful Web 服务(托管在 Azure 中)。这是服务定义:

[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 Store Apps 调用时,我在发布后收到请求错误(它甚至没有命中我在 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 方法都可以正常工作。如果有人能指出我正确的方向,将不胜感激。谢谢!

4

1 回答 1

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");
于 2012-10-25T03:36:10.760 回答