使用REST Web服务的最佳方式是什么?

47 .net rest web-services

从.NET使用REST Web服务的最佳方法是什么?

Sha*_*e K 35

一种直接且简单的方法是使用System.Net命名空间中的WebClient.

几乎所有你需要做的就是以查询字符串形式传递所需的任何参数所需的Uri,你应该以字符串的形式返回响应,无论是json还是xml.例如.

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));
Run Code Online (Sandbox Code Playgroud)

然后,就像Nick提到的那样,您可以根据需要使用XmlDocument或JavaScriptSerializer来操作结果.无论如何,我建议查看它上面的文档,看看它是否符合您的需求.http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx

  • 您需要使用WebClient.UploadData来指定您使用的方法.HttpWebRequest更灵活,可能更适合与REST交互. (4认同)

Cus*_*dio 9

而是使用像Kenney这样的WebClient,您可以使用HttpWebRequest和HttpWebResponse,并使用StreamReader和XmlDocument处理结果.