我有以下代码:
[DataContract]
public class OptimizationServiceSettings
{
[DataMember]
public bool StealthMode { get; set; }
}
服务器:
[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");
}
}
客户端:
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());
}
}
由于某种原因,服务器上的SetSettings
方法始终获得空settings
个对象。如果我将settings
对象类型更改为string
,则一切正常。我不明白这里有什么问题。一切看起来都是正确的。
以下是我在客户端jsonInput
中收到的SetSettings
字符串示例:
"{\"StealthMode\":\"true\"}"
答案 0 :(得分:2)
您指定了要包装的请求对象:
[WebInvoke(..., BodyStyle = WebMessageBodyStyle.WrappedRequest, ...]
因此,如果你将settings-object包装在一个包含的对象中,反序列化只会成功,就像@Pankaj建议的那样。
您可以尝试将属性更改为WebMessageBodyStyle.Bare
,而不是执行此操作,以避免需要包装参数。