WCF JSON POST请求,单个字符串参数未绑定并返回400 [英] WCF JSON POST request, single string parameter not binding and returning 400
问题描述
在我的WCF(天蓝色云)服务中,我想支持JSON.我正在创建一些测试方法,以查看是否一切正常.我可以使用GET调用来工作,但是当我使用简单的参数进行POST时,总会得到:
In my WCF (azure cloud) service, I want to support JSON. I am creating some test methods to see if everything works. I can get the GET calls to work, but when I'm doing a POST with a simple parameter I will always get:
The remote server returned an error: (400) Bad Request.
如果我不发送参数,它将执行该方法,但是当然会使用空值作为参数.我尝试了JSON和WebMessageBodyStyle的不同格式,但似乎都无法正常工作.
If I don't send a parameter, it will execute the method, but with a null value as parameter of course. I tried different formats of JSON and WebMessageBodyStyle, but none seem to work.
如果我将参数类型更改为Stream,则可以接收数据,但是必须手动反序列化.这不是必须的吧?
If I change the parameter type to Stream I receive the data, but I have to manually deserialize it. This shouldn't be necessary right?
接口:
[OperationContract]
[WebInvoke(UriTemplate = "Test",
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string Test(string data);
Impl:
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);
推荐答案
最黄金的组合是在结合了WebMessageBodyStyle.WrappedRequest的JSON代码中使用双引号.
The golden combination was to use double quotes in the JSON code combined with WebMessageBodyStyle.WrappedRequest.
有效的JSON:
string jsonInput = "{\"data\":\"testvalue\"}";
将WebMessageBodyStyle设置为Bare时,以下JSON起作用:
When setting WebMessageBodyStyle to Bare, the following JSON works:
string jsonInput = "\"testvalue\"";
这篇关于WCF JSON POST请求,单个字符串参数未绑定并返回400的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!