WCF JSON POST 请求,单个字符串参数未绑定并返回 400
WCF JSON POST request, single string parameter not binding and returning 400
在我的 WCF (azure cloud) 服务中,我想支持 JSON。我正在创建一些测试方法来查看是否一切正常。我可以让 GET 调用正常工作,但是当我用一个简单的参数执行 POST 时,我总是会得到:
The remote server returned an error: (400) Bad Request.
如果我不发送参数,它会执行该方法,但当然会将空值作为参数。我尝试了 JSON 和 WebMessageBodyStyle 的不同格式,但 none 似乎有效。
如果我将参数类型更改为 Stream,我会收到数据,但我必须手动反序列化它。这不应该是必要的吧?
接口:
[OperationContract]
[WebInvoke(UriTemplate = "Test",
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string Test(string data);
实现:
public string Test(string data)
{
return "result is " + data;
}
测试客户端:
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = System.Text.Encoding.UTF8;
string jsonInput = "{'data':'testvalue'}";
string postResponse = client.UploadString(postUrl, jsonInput);
Console.WriteLine("post response: " + postResponse);
黄金组合是在 JSON 代码中使用双引号并结合 WebMessageBodyStyle.WrappedRequest.
工作JSON:
string jsonInput = "{\"data\":\"testvalue\"}";
将 WebMessageBodyStyle 设置为 Bare 时,以下 JSON 有效:
string jsonInput = "\"testvalue\"";
在我的 WCF (azure cloud) 服务中,我想支持 JSON。我正在创建一些测试方法来查看是否一切正常。我可以让 GET 调用正常工作,但是当我用一个简单的参数执行 POST 时,我总是会得到:
The remote server returned an error: (400) Bad Request.
如果我不发送参数,它会执行该方法,但当然会将空值作为参数。我尝试了 JSON 和 WebMessageBodyStyle 的不同格式,但 none 似乎有效。
如果我将参数类型更改为 Stream,我会收到数据,但我必须手动反序列化它。这不应该是必要的吧?
接口:
[OperationContract]
[WebInvoke(UriTemplate = "Test",
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string Test(string data);
实现:
public string Test(string data)
{
return "result is " + data;
}
测试客户端:
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = System.Text.Encoding.UTF8;
string jsonInput = "{'data':'testvalue'}";
string postResponse = client.UploadString(postUrl, jsonInput);
Console.WriteLine("post response: " + postResponse);
黄金组合是在 JSON 代码中使用双引号并结合 WebMessageBodyStyle.WrappedRequest.
工作JSON:
string jsonInput = "{\"data\":\"testvalue\"}";
将 WebMessageBodyStyle 设置为 Bare 时,以下 JSON 有效:
string jsonInput = "\"testvalue\"";