开发者

RESTful web service in C# code

开发者 https://www.devze.com 2022-12-21 03:50 出处:网络
How do I consume a 开发者_开发技巧RESTful web service in C# code without wcf? Something very simpleUse the WebRequest class. See A REST Client Library for .NET, Part 1.Please use the below code to inv

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:

  1. using Microsoft.Http; --> Available from the REST Starter Kit (Microsoft.Http.dll)

  2. using System.Net;

  3. using System.IO;


Look at the OpenRasta project - it is a REST Architecture Solution Targeting Asp.net.

0

精彩评论

暂无评论...
验证码 换一张
取 消