I have an asp.net MVC2 application that ne开发者_StackOverfloweds to call a web service from the controller. How do I do this? It is a RESTful service that returns Json data.
I cant seem to find a good example.
Thanks
You call it the same way you would do in any ASP.net application, it is not connected to MVC at all.
Either add a reference and use that (easiest) or go with the manual method: here is a guide, see at towards the end (fig. 14 in particular) for consuming such services: http://msdn.microsoft.com/en-us/magazine/dd943053.aspx
I have written my own ActictiveResource client framework, which allows the consumer to specifiy the http provider and the serialisation provider. The generic activeResource class has the four main verbs (get,put,post,delete) as methods which it calls against a specified resource url, passed in at cunstruction. the fololwing is an example of getting a product item from teh service:
ActiveResource<Product> arProduct = new ActiveResource<Product>(jsoSerializer,liveHttpProv,"https://company/product/1452");
//Get verb
Product prod = arProduct.Get();
Of course you can also use the other verbs on the object to put, post and delete.
arProduct.Post(prod);
The code, basically, wraps up the underlying http post,put, get functions and takes care of the serialiasation of the payload to objects. It has been a very useful component which I have used over and over again. The code can be easily called from a controller, it may be worth using a IOC container (I am using Th eUnity block) to instatiate you providers
Hope this helps
I would put together a simple class that acts as a "client" that makes a web-request from the URL, and then return the response as a string.
From there you can deserialize the JSON data using either the JSON serialization that ships with WCF, or the most excellent JSON.Net library. You will need to create a simple data class that is structured in the same way as the JSON data your expecting back.
You could also combine the two and have your client class return the deserialized object directly.
精彩评论