Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume Rest Web service in c#

I have written a webservice which on browser launch works fine. I pass a client id in this webservice and then returns a string containing the client name and it which we passed like this: http://prntscr.com/8c1g9z

My code for creating service is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace RESTService.Lib
{
    [ServiceContract(Name = "RESTDemoServices")]
    public interface IRESTDemoServices
    {
        [OperationContract]
        [WebGet(UriTemplate = "/Client/{id}", BodyStyle = WebMessageBodyStyle.Bare)]
        string GetClientNameById(string Id);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RestDemoServices:IRESTDemoServices
    {
        public string GetClientNameById(string Id)
        {
            return ("Le nom de client est Jack et id est : " +Id);
        }
    }
}

But I am not able to consume it. My code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Http;
using System.Net;
using System.IO;
namespace ConsumerClient
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {   
            System.Net.HttpWebRequest webrequest = (HttpWebRequest)System.Net.WebRequest.Create("http://localhost:8000/DEMOService/Client/156");
            webrequest.Method = "POST";
            webrequest.ContentType = "application/json";
            webrequest.ContentLength = 0;
            Stream stream = webrequest.GetRequestStream();
            stream.Close();
            string result;
            using (WebResponse response = webrequest.GetResponse()) //It gives exception at this line liek this http://prntscr.com/8c1gye
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                    Label1.Text = Convert.ToString(result);
                }
            }
        }
    }
}

I get an exception like this http://prntscr.com/8c1gye How to consume the web service. Could someone please help me ?

like image 374
xav xav Avatar asked Sep 03 '15 07:09

xav xav


1 Answers

The exception is pretty clear - you can't use POST if you want to retrieve data from a REST service, unless it allows it. You should use GET instead of POST, or simply don't change request.Method. By default it's GET.

You don't need to do anything special to "consume" REST services - essentially they work just like any other URL. The HTTP POST verb means that you want to create a new resource, or post form data. To retrieve a resource (page, API response etc) you use GET.

This means that you can use any of the HTTP-related .NET classes to call a REST service - HttpClient (preferred), WebClient or raw HttpWebRequest.

SOAP services used POST both for getting and sending data, which is now considered a design mistake by everyone (including the creators of SOAP).

EDIT

To make this clear, using a GET means there is no content and no content related headers or operations are needed or allowed. It's the same as downloading any HTML page:

var url="http://localhost:8000/DEMOService/Client/156";
var webrequest = (HttpWebRequest)System.Net.WebRequest.Create(url);

using (var response = webrequest.GetResponse()) 
using (var reader = new StreamReader(response.GetResponseStream()))
{
    var result = reader.ReadToEnd();
    Label1.Text = Convert.ToString(result);
}

You can even paste the URL directly to a browser to get the same behaviour

like image 64
Panagiotis Kanavos Avatar answered Oct 07 '22 22:10

Panagiotis Kanavos