RESTful WCF wrapping json response with method name
Asked Answered
N

2

11

I am pretty new to RESTful WCF services so bear with me. I am trying to build a simple RESTful WCF service that returns a List of Students as json response. All works well until the point where I try to convert the json string back to list of Student objects on the client.

Here is my operation contract:

[OperationContract]
[WebGet(UriTemplate = "Students/", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
public List<Student> FetchStudents()
{
//Fetch and return students list
}

Client code:

static void Main(string[] args)
{
HttpClient client = new HttpClient("http://localhost/StudentManagementService/StudentManagement.svc/");
response = client.Get("Students/");
response.EnsureStatusIsSuccessful();
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
string str = response.Content.ReadAsString();
List<Student> st = json_serializer.Deserialize<List<Student>>(str);
}

This code obviously fails because the json string returned by the service looks like below:

{"FetchStudentsResult":[{"Course":"BE","Department":"IS","EmailID":"[email protected]","ID":1,"Name":"Vinod"}]}

For some reason the json response is getting wrapped inside the FetchStudentsResult. Now in debug mode if I forcefully remove this FetchStudentsResult wrap, my deserialization works perfectly fine.

I have tried DataContractJsonSerializer but the result is exactly the same. Can someone tell me what am I missing?

Nutwood answered 16/2, 2012 at 14:11 Comment(0)
N
26

Ok, I have figured it out myself. The problem is the below line:

BodyStyle = WebMessageBodyStyle.Wrapped

When I changed this to:

BodyStyle = WebMessageBodyStyle.Bare

Everything works perfectly!

Thanks!

Nutwood answered 17/2, 2012 at 3:22 Comment(0)
O
1

In my case, It was WebInvoke instead of WebGet and I was sending data in body. Because of that this solution didnt work for me. I have used the one below and it worked.

BodyStyle = WebMessageBodyStyle.RequestWrapped

So in post, the body should be wrapped but no need in response. Thanks for the questioner and his answer for giving a clue about this problem.

Orosco answered 6/6, 2019 at 6:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.