1

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

1

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.