Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Rest WCF Service operation from C# when BodyStyle = WebMessageBodyStyle.Wrapped

Tags:

rest

c#

wcf

web

I'm using a rest based wcf service that has a operation defined that I want to consume. The definition of the BodyStyle is set to WebMessageBodyStyle.Wrapped.

Could someone please suggest how I could read the return value from the service using .net without making server side changes?

Can I convert the response stream into a serialized object from the DataContractJsonSerialized function when the wcf rest operation has the BodyStyle set to WebMessageBodyStyle.Wrapped?

The following is the definition of the wcf service method

[OperationContract]
    [WebGet(BodyStyle = WebMessageBodyStyle.Wrapped,RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json,UriTemplate = "CheckStatus/{id}")]
    CurrentStatus CheckStatus(string id);

The CurrentStatus data contract is defined as

[DataContract]
public class CurrentStatus
{
    [DataMember(Name = "message")]
    public string message { get; set; }
    [DataMember(Name = "value")]
    public int value { get; set; }
}

If the WebMessageBodyStyle is set to Bare, as the following code shows then the calls works as expected. If the WebMessageBodyStyle is set to wrapped then the message and value datamembers are always read blank even though the server is responding with the expected values. This is seen by calling through a web browser.

I am trying to modify this consuming code to read the json content inside the wrapper.

[OperationContract]
    [WebGet(BodyStyle = WebMessageBodyStyle.Bare,RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json,UriTemplate = "CheckStatus/{id}")]
    CurrentStatus CheckStatus(string id);

//Client code Works if server operation contarct BodyStyle=WebMessageBodyStyle.Wrapped
string uri = "http://TestServer/WCF/WCF.svc/CheckStatus/{7}"
byte[] data = proxy.DownloadData(uri);
Stream stream = new MemoryStream(data);
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof (CurrentStatus));
CurrentStatus status = obj.ReadObject(stream) as CurrentStatus;
Console.WriteLine(status.message);
Console.WriteLine(status.value);

When the uri called inside a browser the following are sample responses

If the BodyStyle is WebMessageBodyStyle.Bare a sample response is

{"message":"New","value":1}

When the BodyStyle is WebMessageBodyStyle.Wrapped a sample response is

{"CheckStatusResult":{"message":"New","value":1}}

Thanks in advance

like image 626
user3199045 Avatar asked Nov 11 '22 14:11

user3199045


1 Answers

will the one below work? i haven't tested it.

public class CurrentStatusWrapper 
{
    public CurrentStatus CheckStatusResult {get; set;}
}

DataContractJsonSerializer obj = 
                      new DataContractJsonSerializer(typeof (CurrentStatusWrapper));
like image 159
Yang You Avatar answered Nov 14 '22 21:11

Yang You