C# WCF服务没有';无法识别正确的JSON
我有以下代码:C# WCF服务没有';无法识别正确的JSON,c#,json,wcf,C#,Json,Wcf,我有以下代码: [DataContract] public class OptimizationServiceSettings { [DataMember] public bool StealthMode { get; set; } } 服务器: [WebInvoke(Method = "POST", UriTemplate = "SetSettings", BodyStyle = WebMessageBodyStyle.WrappedRequest, Response
[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());
}
}
您指定了要包装的requestbody:
[WebInvoke(..., BodyStyle = WebMessageBodyStyle.WrappedRequest, ...]
因此,如@Pankaj所建议的,只有将设置对象包装在包含对象中,反序列化才会成功
您可以尝试将属性更改为
WebMessageBodyStyle.Bare
,而不必包装参数。您发布的是什么json字符串?您能在这里发布jsonInput变量的值吗?@PankajKapare addedTry发送请求json类似于以下内容{“设置”:{“StealthMode”:“true”}@PankajKapare有没有办法不手动使用序列化程序?
[WebInvoke(..., BodyStyle = WebMessageBodyStyle.WrappedRequest, ...]