[英]WCF service doesn't recognise correct JSON
I have the following code: 我有以下代码:
[DataContract]
public class OptimizationServiceSettings
{
[DataMember]
public bool StealthMode { get; set; }
}
Server: 服务器:
[WebInvoke(Method = "POST", UriTemplate = "SetSettings", BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
[OperationContract]
public void SetSettings(OptimizationServiceSettings settings)
{
if (settings != null)
{
_stageOptimizer.ServiceSettings = settings;
}
else
{
Trace.TraceError("Attemp to set null OptimizationServiceSettings");
}
}
Client: 客户:
private static void SetSettings()
{
OptimizationServiceSettings op = new OptimizationServiceSettings();
op.StealthMode = true;
string jsonInput = ToJson(op);
var client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
var response = client.UploadString("http://localhost:8080/BlocksOptimizationServices/SetSettings", "POST", jsonInput);
}
private static string ToJson<T>(T data)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, data);
return Encoding.Default.GetString(ms.ToArray());
}
}
For some reason the SetSettings
method on the server always gets a null settings
object. 由于某种原因,服务器上的SetSettings
方法始终获得一个null settings
对象。 If I change the settings
object type to string
it all works. 如果我将settings
对象类型更改为string
则一切正常。 I don't understand what is wrong here. 我不明白这里出了什么问题。 Everything looks like it is correct. 一切看起来都是正确的。
Here is an example of the jsonInput
string that I got in SetSettings
on the client: 这是我在客户端的SetSettings
获得的jsonInput
字符串的示例:
"{\"StealthMode\":\"true\"}"
You specified the requestbody to be wrapped: 您指定了要包装的请求正文:
[WebInvoke(..., BodyStyle = WebMessageBodyStyle.WrappedRequest, ...]
Hence, the deserialization only succeeds if you wrap the settings-object within a containing object, as @Pankaj suggested. 因此,只有在将设置对象包装在包含对象的情况下,反序列化才能成功,如@Pankaj建议的那样。
Instead of doing that, you could try to change the attribute to WebMessageBodyStyle.Bare
to avoid the need to wrap the parameter. 代替这样做,您可以尝试将属性更改为WebMessageBodyStyle.Bare
以避免需要包装参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.