James
James

Reputation: 11

RESTful web service in C# code

How do I consume a RESTful web service in C# code without wcf? Something very simple

Upvotes: 1

Views: 3035

Answers (3)

Rajesh
Rajesh

Reputation: 7876

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;

Upvotes: 2

Oded
Oded

Reputation: 498904

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

Upvotes: 0

John Saunders
John Saunders

Reputation: 161773

Use the WebRequest class. See A REST Client Library for .NET, Part 1.

Upvotes: 2

Related Questions