Click here to Skip to main content
15,883,928 members
Please Sign up or sign in to vote.
3.67/5 (3 votes)
See more:
Hi Dear:
I have Created a Restful Service in C#, and Now i want to use my this Service in C# Restful Client. Client may be a Console Client, but Asp.net Client is preferred.
I have tried a lot more Tutorials, but no Success till now,
Please suggest me some Working Sample,

My Project code is as follow:
Here is the code of Web.Config File in Servie Project:

XML
<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>

    <services>
      <service name="Restful.Restful" behaviorConfiguration="ServiceBehaviour">
        <endpoint address="" binding="webHttpBinding" contract="Restful.IRestful" behaviorConfiguration="web">

        </endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name ="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>



My IRestful.cs Code


My Project(Restful Service) Name is Restful,
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace Restful
{
    [ServiceContract]
    public interface IRestful
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "name/id={id}")]
        string test(string id);

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "xml/?id={id}")]
        string xdata(string id);

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/?id={id}")]
        string jdata(string id);

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "sum/?a={a}&b={b}")]
        string sum(int a, int b);
    }
}


My Restful.svc.cs Code:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Restful
{
    public class Restful : IRestful
    {
        #region IRestService Members

        public string test(string id)
        {
            return "Testing Phase is Continued. :" + id;
        }
        public string xdata(string id)
        {
            return "Your Requested XML Product is :" + id;
        }

        public string jdata(string id)
        {
            return "Your Requested XML Product is :" + id;
        }

        public string sum(int a, int b)
        {
            return "Sum of Numbers is: " + (a + b);
        }

        #endregion
    }
}



I have Tried to Consume Service using ASP.net, My ASP.net project name is WebClient
Here is the code of WebForm.aspx.cs File:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Http;

namespace WebClient
{
    public partial class WebForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage msg = client.GetAsync("http://localhost:27629/Restful.svc/sum/?a=23&b=90").ContinueWith<httpresponsemessage>;
            HttpContent strm = msg.Content();
            var data = strm.ReadAsStreamAsync();
            Label1.Text = Convert.ToString(data.Result);
        }
    }
}


Here is the code of WebForm.aspx file:

XML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm.aspx.cs" Inherits="WebClient.WebForm" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <div>

    </div>
    </form>
</body>
</html>




Please refer me tos solution, that may lead to get rid of this problem....
Thanks In Advance...
Posted
Updated 11-Sep-13 8:04am
v2
Comments
Eytukan 12-Sep-13 5:41am    
Why is this under C++ questions? :suss:

There are two ways to get the data from service one is XML and other one is JSON.
you chose xml the data you received is in the format of XML schema you only have to convert it into required format.
I just give you an example,

HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("your url with args");
webrequest.Method = "POST";
webrequest.ContentType = "application/json";
webrequest.ContentLength = 0;
Stream stream = webrequest.GetRequestStream();
stream.Close();
string result;
using (WebResponse response = webrequest.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
}


The result variable contains xml schema as string
So, now convert into as per your need.

For that you need to send the data into your required need like string, list or dataset
from the service.
The difficult one is retreiving the dataset from the service which contains a list of records with number of columns.
I just give you the core snippet

DataSet ds = new DataSet();
ds.Tables.Clear();
XmlElement exelement;
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);//Load the XML schema string into a XML document
exelement = doc.DocumentElement;//Get the XML element from the document
if (exelement != null)
{
XmlNodeReader nodereader = new XmlNodeReader(exelement);/read the nodes in the XML element
ds.ReadXml(nodereader, XmlReadMode.Auto);//Read the XML nodes and load it in the dataset
}


Hope it helps...!
 
Share this answer
 
Comments
Member 8775683 12-Sep-13 1:54am    
Dear I implemented your this code in my own setting, but Again I have to face:

[WebException: The remote server returned an error: (405) Method Not Allowed.]
System.Net.HttpWebRequest.GetResponse() +6440920
WebClient.WebForm.Button1_Click(Object sender, EventArgs e) in e:\Visual Studio\Restful\WebClient\WebForm.aspx.cs:33
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553594
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724


This is the Major Cause of problem:
WebResponse resp = req.GetResponse();
The remote server returned an error: (405) Method Not Allowed.
Member 8775683 12-Sep-13 2:05am    
Dear Please Post an Article for me in which you Simply have Added two Numbers,
But Please First develop a Restful Service for addition of two numbers and then Create a Restful Client using that Service,
Please do if you can,
Thanks,
or tell any way so I can send you my coding files in Zip Format, and you change it simply,
Infact I am New to this Technology and will be Thankful if you get me Rid of this problem,
Thanks...
Dear Member 8775683 i understand you, i also learnt this some days ago. If i did the coding to you means you dont get learnt on yourself.
So i just gave you clear idea soon i will write an article so that help you.

This is my service,
C#
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate="CheckLogin/{userName}/{password}")]
string CheckLogin(string userName,string password);


I checked the data and returns a string value only in json format.
C#
public string CheckLogin(string userName, string password)
        {
            try
            {
                ds = null;
                data = "";
                integerValue = dbServices.CheckLogin(userName, password);
                if (integerValue >= 1)
                {
                    Status= "SUCCESS";
                }
                else
                    Status= "FAILED";
            }
            catch (Exception ex)
            {
            }
            return Status;
        }


and i consume it at the client side as following,

HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url + "CheckLogin" + "/" + txtUserName.Text.Trim().ToString() + "/" + txtPassword.Text.Trim().ToString());
                   webrequest.Method = "POST";
                   webrequest.ContentType = "application/json";
                   webrequest.ContentLength = 0;
                   Stream stream = webrequest.GetRequestStream();
                   stream.Close();
                   string result;
                   using (WebResponse response = webrequest.GetResponse())
                   {
                       using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                       {
                           result = reader.ReadToEnd();
                       }
                   }
                   result = result.Substring(1, result.Length - 2);

i just hand code the string result value to get my need.
you may JSON serialize and deserialize methods to get the data as you need.

You may get that JSON methods from the following link.
http://james.newtonking.com/projects/json-net.aspx[^]

It may help you

and to answer the error you got faced is occured during the consumption
look these following links you may get some ideas
how-to-consume-or-use-wcf-service[^]
how-to-consume-wcf-service-in[^]
http://technetsharp.wordpress.com/2012/04/18/use-wcf-service-in-web-application-for-beginners/[^]
 
Share this answer
 
Comments
rishi_hamza 21-Nov-15 9:04am    
thanks Man, Your code help me to find my solution after 1.5 days :-) Best Regards

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900