c# - 使用 JSON 的 WCF RESTful POST,来自 Windows 应用商店应用

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

我正在从我的 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))
    {
        // ...
    }
}

我认为可能是内容类型 header 有问题(上次检查它被设置为纯文本,但我找不到更改它的方法)。

HTTP GET 方法都工作正常。如果有人能指出我正确的方向,我将不胜感激。谢谢!

最佳答案

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

关于c# - 使用 JSON 的 WCF RESTful POST,来自 Windows 应用商店应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13060905/

相关文章:

java - 寻找 JsonParser 依赖

c# - 超出 WCF MaxConcurrentSessions

c# - WCF:如何为类型中的类型构造 DataContract

.net - WCF 中的 Web 服务发现 : Ws-Discovery or UDDI?

c# - 简单的if语句

arrays - UITableViewCell 如何知道要从数组或字典加载什么 JSON

c# - 如何将 javascript 中的 JSON 数组传递到我的代码隐藏文件

ios - 如何在ios swift中将对象数组转换为Json数组或Json字符串?

c# - Entity Framework 多对象上下文

c# - Asp.Net 页面生命周期 - 什么工具(也许是 Reflector?)可以让我查看调用页面事件及其事件处理程序的顺序