2

I'm having difficulty consuming a WCF REST service, which returns JSON, in a C# ASP.NET MVC application. I'm trying to consume the service in a Controller. I have a ASP.NET MVC project and a service project in the same solution. I've created an entry in my local IIS which points to the service project (i.e. http://localhost/SampleService/).The WCF Service works because I can access the URL and the correct JSON is returned.

Does anyone have any code samples on consuming the JSON via a Controller from a RESTful WCF Service?

3 Answers 3

3

You can use the DataContractJsonSerializer:

Here's an example:

var client = new WebClient();
var data = client.DownloadData("http://localhost/SampleService/GetJsonMessage");
var stream = new MemoryStream(data);
var obj = new DataContractJsonSerializer(typeof(string));
var result = obj.ReadObject(stream).ToString();

In your controller you can do this to view the result

return Content(result.ToString())
Sign up to request clarification or add additional context in comments.

Comments

1

I used WebChannelFactory and it worked great.

Comments

0

You can either use the built-in DataContractJsonSerializer, or the JSON.NET library's JsonSerializer.

I prefer the latter, because it is more robust. Sometimes the DataContractJsonSerializer cannot deserialize a JSON object.

Sample code:

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonText);

To download the library, go to http://json.codeplex.com/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.