【问题标题】:WCF RESTful POST using JSON, from Windows Store App使用 JSON 的 WCF RESTful POST,来自 Windows Store App
【发布时间】:2012-10-25 02:57:40
【问题描述】:

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

【问题讨论】:

    标签: c# json wcf microsoft-metro windows-store-apps


    【解决方案1】:

    您应该在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");
    

    【讨论】:

    • 不敢相信我错过了那个构造函数。非常感谢!现在它正在工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2012-08-07
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多