Brans Ds
Brans Ds

Reputation: 4117

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. If I change the settings object type to string it all works. 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:

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

Upvotes: 1

Views: 49

Answers (1)

Jan K&#246;hler
Jan K&#246;hler

Reputation: 6030

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.

Instead of doing that, you could try to change the attribute to WebMessageBodyStyle.Bare to avoid the need to wrap the parameter.

Upvotes: 2

Related Questions