简体   繁体   中英

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:

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

  2. using System.Net;

  3. using System.IO;

看看OpenRasta项目 - 它是一个针对Asp.net的REST架构解决方案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM