What is the best way to consume REST web services?

2019-03-08 03:21发布

What's the best way to consume REST web services from .NET?

7条回答
孤傲高冷的网名
2楼-- · 2019-03-08 03:34

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.

查看更多
萌系小妹纸
3楼-- · 2019-03-08 03:36

Instead using WebClient like Kenney, you can use HttpWebRequest and HttpWebResponse and process the result with a StreamReader and XmlDocument .

查看更多
女痞
5楼-- · 2019-03-08 03:37

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

查看更多
混吃等死
6楼-- · 2019-03-08 03:38

There is also RestSharp, a lightweight .NET component that lets you easily consume REST web services

查看更多
你好瞎i
7楼-- · 2019-03-08 03:39

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

查看更多
登录 后发表回答