【问题标题】:WCF service doesn't recognise correct JSONWCF 服务无法识别正确的 JSON
【发布时间】:2016-03-25 22:40:10
【问题描述】:

我有以下代码:

[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 一切正常。我不明白这里有什么问题。一切看起来都是正确的。

下面是我在客户端SetSettings 中得到的jsonInput 字符串示例:

"{\"StealthMode\":\"true\"}"

【问题讨论】:

  • 你发布的是什么 json 字符串?你可以在这里发布 jsonInput 变量的值吗?
  • @PankajKapare 添加
  • 尝试发送类似这样的请求 json { "settings" : {"StealthMode":"true"}}
  • @PankajKapare 有没有办法用序列化器不手动地做到这一点?

标签: c# json wcf


【解决方案1】:

您指定了要包装的请求体:

[WebInvoke(..., BodyStyle = WebMessageBodyStyle.WrappedRequest, ...]

因此,只有按照@Pankaj 的建议将设置对象包装在包含对象中时,反序列化才会成功。

您可以尝试将属性更改为WebMessageBodyStyle.Bare,而不是这样做,以避免需要包装参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2017-06-21
    相关资源
    最近更新 更多