How to consume Rest Web service in c#
Asked Answered
J

2

5

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 like 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 ?

Jablon answered 3/9, 2015 at 7:14 Comment(1)
[WebGet] means webrequest.Method = "GET".Mahatma
P
15

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

Parapodium answered 3/9, 2015 at 7:22 Comment(7)
Additional information: Cannot send a content-body with this verb-type. at line Stream stream = webrequest.GetRequestStream(); after GETJablon
Why pass a body? You've defined an action with an Id parameter, with the Id actually as part of the URL. Put the ID in the request Url. A simple web request for http://localhost:8000/DEMOService/Client/156 is enough. Even a WebClient.GetString on the URL will workParapodium
thanks for the answer.. But i have doen the same in consumer code . please see : System.Net.HttpWebRequest webrequest = (HttpWebRequest)System.Net.WebRequest.Create("localhost:8000/DEMOService/Client/156"); But still do nto workJablon
It's the rest of the code that acts as if you are trying to make a POST - you don't need to specify a content type or do anything with the request stream. Just call request.GetResponse() immediately, as you would in when trying to call any URLParapodium
raw HttWebRequest. is a typo.Spar
But if you see my GetClientNameById(string Id) function n web service at start. It will only be called when i pass Id.Jablon
The exception complains about the request content and headers, not the parameter. GET is like typing the URL in a web browser - if you can get a response in the browser, you can get a response using HttpWebRequest using only the URLParapodium
W
-1

This code example is a simple example of how to consume a REST web service in C#:

// http://localhost:{portno}/api/v1/youractionname?UserName=yourusername&Passowrd=yourpassword [HttpGet]

[ActionName("Youractionname")]

public Object Login(string emailid, string Passowrd)
{
    if (emailid == null || Passowrd == null)
    {
        geterror gt1 = new geterror();
        gt1.status = "0";
        gt1.msg = "All field is required";
        return gt1;
    }
    else
    {
        string StrConn = ConfigurationManager.ConnectionStrings["cn1"].ConnectionString;
        string loginid = emailid;
        string Passwrd = Passowrd;
        DataTable dtnews = new DataTable();
        SqlConnection con = new SqlConnection(StrConn);
        con.Open();
        SqlCommand cmd = new SqlCommand("sp_loginapi_app", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p1 = new SqlParameter("@emailid", loginid);
        SqlParameter p2 = new SqlParameter("@password", Passowrd);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add(p1);
        cmd.Parameters.Add(p2);
        da.Fill(dtnews);
        if (dtnews.Rows[0]["id"].ToString() == "-1")
        {
            geterror gt1 = new geterror();
            gt1.status = "0";
            gt1.msg = "Invalid Username or Password";
            con.Close();
            return gt1;
        }
        else
        {
            dtmystring.Clear();
            dtmystring.Columns.Add(new DataColumn("id", typeof(int)));
            dtmystring.Columns.Add(new DataColumn("Name", typeof(string)));
            dtmystring.Columns.Add(new DataColumn("Password", typeof(string)));
            dtmystring.Columns.Add(new DataColumn("MobileNo", typeof(string)));
            dtmystring.Columns.Add(new DataColumn("Emailid", typeof(string)));
            DataRow drnew = dtmystring.NewRow();
            drnew["id"] = dtnews.Rows[0]["id"].ToString();
            drnew["Name"] = dtnews.Rows[0]["Name"].ToString();
            drnew["Password"] = dtnews.Rows[0]["Password"].ToString();
            drnew["MobileNo"] = dtnews.Rows[0]["MobileNo"].ToString();
            drnew["Emailid"] = dtnews.Rows[0]["emailid"].ToString();
            dtmystring.Rows.Add(drnew);
            gt.status = "1";
            gt.msg = dtmystring;
            con.Close();
            return gt;
        }
    }
}
Wolenik answered 17/3, 2016 at 7:18 Comment(4)
Good example of Rest web services in c#.Obtrude
Thanks @Mannam Brahmam!Wolenik
it is very simple example of rest web api.Wolenik
Actually, this is not a REST consumer example at all, it's an example of a REST service itself, and doesn't show how to consume it. Also, there's a lot of code here that deals with databases which is unrelated to the subject of REST. You may want to improve your answer to show how to consume it.Pedigree

© 2022 - 2024 — McMap. All rights reserved.