RESTful web service in C# code
How do I consume a 开发者_开发技巧RESTful web service in C# code without wcf? Something very simple
Use the WebRequest class. See A REST Client Library for .NET, Part 1.
Please use the below code to invoke a RESTful web service.
string responseMessage;
HttpClient client = new HttpClient(serviceUrl);
HttpWebRequest request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
request.ContentType = "text/xml";
request.Method = method;
HttpContent objContent = HttpContentExtensions.CreateDataContract(requestBody);
if(method == "POST" && requestBody != null)
{
//byte[] requestBodyBytes = ToByteArrayUsingXmlSer(requestBody, "http://schemas.datacontract.org/2004/07/XMLService");
byte[] requestBodyBytes = ToByteArrayUsingDataContractSer(requestBody);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
//request.Timeout = 60000;
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
else
{
responseMessage = response.StatusDescription;
}
The above code needs to refer the following namespaces:
using Microsoft.Http; --> Available from the REST Starter Kit (Microsoft.Http.dll)
using System.Net;
using System.IO;
Look at the OpenRasta project - it is a REST Architecture Solution Targeting Asp.net.
精彩评论