What's the best way to consume REST web services from .NET?
问题:
回答1:
A straight forward and easy approach would be to use WebClient which is in the System.Net namespace.
Pretty much all you need to do is pass in the Uri required with any parameters needed in the form of a query string and you should get back the response in the form of a string, be it json or xml. For example.
using System.Net;
string param = "hello";
string url = String.Format("http://somedomain.com/samplerequest?greeting={0}",param);
WebClient serviceRequest = new WebClient();
string response = serviceRequest.DownloadString(new Uri(url));
Then, like Nick mentioned, you can use XmlDocument or JavaScriptSerializer to manipulate the results as needed. Anyway I suggest checking out the documentation on it to see if it meets your needs. http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
回答2:
Instead using WebClient like Kenney, you can use HttpWebRequest and HttpWebResponse and process the result with a StreamReader and XmlDocument .
回答3:
There is also RestSharp, a lightweight .NET component that lets you easily consume REST web services
回答4:
Probably WCF; check out
http://hyperthink.net/blog/announcing-the-wcf-rest-starter-kit/
回答5:
In my opinion, the easiest way to implement a REST API is to use Service Stack:
http://www.servicestack.net/
I my last Windows project I made a proof of concept in WCF and ServiceStack and the Service Stack application was faster (you can look for measurements in the Service Stack site) and easier to maintain (less code, less magic implementation). And the most important point, it helps you to focus in simplicity.
回答6:
Do you want to consume or publish. If you want to consume, such as making requests the best way to interact with it is to figure out the type it will comback as, usually JSON or XML. After you have your type you can use XmlDocument or JavaScriptSerializer to pull back the information and use it.
If you want to produce a REST interface then you probably want to use either MVC a REST View or WCF as @Brian said.
回答7:
If the REST services were built using ASP.NET Web API then I would use the Microsoft Http Client Libraries. (nuget package available). N.B. This appears to have superseded the web api client libraries that are listed in the nuget screenshot on the link below.
This will work from .NET 4, Windows Store Apps, Windows Phone 7.5/8, Silverlight 4 and 5.
In theory you could use it to call any REST service built with other frameworks as well.
Here's a link with some samples on using the HttpClient class to call REST services: Calling a web api from a .net client