cpeele00
cpeele00

Reputation: 893

How do I consume a non-wcf rest service in asp.net mvc 3?

I have a simple web service I wrote using Webmatrix that returns data in json. I liked to consume that service using ASP.NET MVC 3. I know how to do this with WCF but we are not going to use WCF on this project. Is there something akin to jquery's getJson() method in ASP.NET MVC where I just pass in the restful url and it returns the data and I handle it in a callback? Thanks for any help :-)

Here's my service:

URL:

 /services/GetAllItemsService

Code:

@{
    var items = ItemsService.GetAllItems();

    Json.Write(items, Response.Output);
 }

Upvotes: 3

Views: 2488

Answers (3)

ccellar
ccellar

Reputation: 10344

  • Use some lib like RestSharp, Hammock, ...
  • Retrieve the data with WebClient and use a JSON deserializer like JavaScriptSerializer or Json.NET

Upvotes: 0

Jesse
Jesse

Reputation: 8393

Take a look at RESTSharp: http://restsharp.org/

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could use a WebClient to fetch the JSON data from a remote resource. For example:

using (var client = new WebClient())
{
    string json = client.DownloadString("http://example.com/services/GetAllItemsService");

    // TODO: do something with this JSON data, like for example deserialize into a model
    var serializer = new JavaScriptSerializer();
    var model = serializer.Deserialize<SomeModel>(json);
}

Or if you wanted to write the JSON directly to the output:

using (var client = new WebClient())
{
    string json = client.DownloadString("http://example.com/services/GetAllItemsService");
    Response.Output.Write(json);
}

Upvotes: 4

Related Questions