1
我有以下代碼:WCF服務不能識別正確的JSON
[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\"}"
你正在發佈什麼json字符串?你可以在這裏發佈jsonInput變量的值嗎? –
@ PankajKapare新增 –
嘗試發送請求json是這樣的{「settings」:{「StealthMode」:「true」}} –