我正在从我的 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/