6

My contract details are below. I am using Json response and request format and also using POST method. How to write a client to consume this service in c#.

[OperationContract()]
[WebInvoke(UriTemplate = "/RESTJson_Sample1_Sample1Add", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
int RESTJson_Sample1_Sample1Add(Int32 a, Int32 b, Int32 c);
ranieuwe
  • 2,268
  • 1
  • 24
  • 30
senthil kumar
  • 151
  • 1
  • 2
  • 9
  • 4
    Please don't just ask us to solve the problem for you. Show us how _you_ tried to solve the problem yourself, then show us _exactly_ what the result was, and tell us why you feel it didn't work. See "[What Have You Tried?](http://whathaveyoutried.com/)" for an excellent article that you _really need to read_. – John Saunders Jul 13 '13 at 00:10

4 Answers4

3

try as below:

   [OperationContract()]
   [WebInvoke(UriTemplate = "/RESTJson_Sample1_Sample1Add?A=a&B=b&C=c", Method = "POST",  
     RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,   
     BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    int RESTJson_Sample1_Sample1Add(Int32 a, Int32 b, Int32 c);

       var httpWebRequest = (HttpWebRequest)WebRequest.Create("/RESTJson_Sample1_Sample1Add?A=a&B=b&C=c");
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = methodType;//POST/GET
        string responseText = "";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(body);//any parameter
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            responseText = streamReader.ReadToEnd();
        }
        return responseText;
Amit
  • 15,217
  • 8
  • 46
  • 68
  • Nice example. A question. The "serviceURL" your passing into the WebRequest.Create method is the RESTful Uri htttp://{domain name}/RestJson_Sample... (using the example above)? – beaumondo Jul 10 '13 at 08:02
  • suppose if i have 3 integer parameter, how can i pass this? – senthil kumar Jul 10 '13 at 09:13
  • since, we are using POST method, but here we are passing value via query string. Is that correct? – senthil kumar Jul 10 '13 at 09:55
  • 1
    My Uri template should be like this "UriTemplate = "/RESTJson_Sample1_Sample1Add". by having this how can i pass three parameters via client? And also plz let me know what should i pass in "body" parameter in your example. – senthil kumar Jul 10 '13 at 09:57
  • i am getting error at "var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();" Error Details: The remote server returned an error: (404) Not Found. – senthil kumar Jul 10 '13 at 10:28
3

Here I have working code for POST method in WCF REST:-

First create database table with id,uname and pwd fields. create a stored procedure to insert values.

create  procedure [dbo].[sproc_Insertusers]
(
@id int out,
@uname nvarchar(50),
@pwd nvarchar(50)
)
as insert into tbl_register
(
[uname],
[pwd]
)
values
(
@uname,
@pwd
)

set @id = @@identity
return @id

Create new WCF project

in IService1.cs

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "user_register/{uname}/{pwd}")]
        int user_register(string uname,string pwd);
    }

in Service1.cs

 public class Service1 : IService1
    {
        SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["iwealth_db"]);
        SqlCommand cmd;
        DataSet ds;
        SqlDataAdapter da;
        int result;
        public int user_register(string uname, string pwd)
        {
            cmd = new SqlCommand("sproc_Insertusers", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@uname",uname);
            cmd.Parameters.AddWithValue("@pwd", pwd);
            cmd.Parameters.Add("@id", SqlDbType.Int);
            cmd.Parameters["@id"].Direction = ParameterDirection.Output;//Output parameter 

            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();

            result = (int)(cmd.Parameters["@id"].Value);
            return result;//returning id 
        }
    }

in web.config:-

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="iwealth_db"  value="Data Source=localhost;Initial Catalog=iwealth; Trusted_Connection=true"/>      
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="iWealthService.Service1" behaviorConfiguration="ServiceBehaviour">
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address ="" binding="webHttpBinding" contract="iWealthService.IService1" behaviorConfiguration="web">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="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>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

Build the WCF. Now, the below code is how to use or consume this WCF service

Create new website

Add register button to test this WCF service

and on button click code:-

 protected void Button1_Click(object sender, EventArgs e)
    {
//in 'sURL' paste WCF service link up to .svc and write -> /user_register/Prateek/1234 
//here user_register is service method path and Prateek and 1234 are parameters that will enter to database 


        string sURL = "http://localhost:49271/Service1.svc/user_register/Prateek/1234";

        WebRequest wrGETURL;
        wrGETURL = WebRequest.Create(sURL);
        wrGETURL.Method = "POST";
        wrGETURL.ContentType = @"application/json; charset=utf-8";
        HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;

        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        // read response stream from response object
        StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
        // read string from stream data
        strResult = loResponseStream.ReadToEnd();
        // close the stream object
        loResponseStream.Close();
        // close the response object
        webresponse.Close();
        // assign the final result to text box
        Response.Write(strResult);
    }
Prateek Gupta
  • 880
  • 1
  • 10
  • 21
  • 1
    Thanks Prateek Gupta,for sharing code.It help me lot.For restful service there is no need to add service reference while consuming service,is it so?Actually I was trying to add service reference while consuming .That's why my client web config file was not containing endpoint.Ur code helped me.Can I consume service directly through browser.Means enter url in browser and hit.'http://localhost:49271/Service1.svc/user_register/Prateek/1234'.I want like this.Means client can enter url in browser and hit,after hitting client want acknowlegment – Jui Test Nov 14 '16 at 12:38
  • 1
    The above example is of 'POST' method. If you put 'GET' in IService1.cs file, this will work in browser too. – Prateek Gupta Nov 15 '16 at 10:01
  • thanks for ur comment.I have done that it is working properly.I am able to test it through browser.But better to use post method instead of get.Now we r giving interface to client for checking url request.So no need of browser. – Jui Test Nov 15 '16 at 10:36
3

To consume WCF Restful service, there is no need of making changes in Web.config. find the below code to consume the POST method of WCF restful service.

        DataContractJsonSerializer objseria = new DataContractJsonSerializer(typeof(StudentDetails));
        MemoryStream mem = new MemoryStream();
        objseria.WriteObject(mem, stu);
        string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
        WebClient webClient = new WebClient();
        webClient.Headers["Content-type"] = "application/json";
        webClient.Encoding = Encoding.UTF8;
        webClient.UploadString("http://localhost:62013/Service1.svc/ADDStudent", "POST", data);

Reference link

K Raghava Reddy
  • 147
  • 1
  • 3
0

If you want to consume a REST service from C# you can take a look at RestSharp. Note that with WCF you can also expose the same method using a basicHttp binding on a different endpoint and consume it using SOAP.

You can also take a look at WebChannelFactory, look at this MSDN tutorial towards the end of the article.

ranieuwe
  • 2,268
  • 1
  • 24
  • 30
  • Hi, Is there any other way to consume this using C#? – senthil kumar Jul 10 '13 at 07:59
  • Not in an easy way using just the .NET framework, no. There is an extension released by Microsoft called HttpClient at http://nuget.org/packages/HttpClient document can be found at http://www.bizcoder.com/index.php/2012/01/09/httpclient-it-lives-and-it-is-glorious/ – ranieuwe Jul 10 '13 at 08:02
  • 1
    Also, take a look at this similar post http://stackoverflow.com/questions/8883656/how-to-consume-a-restful-service-in-net – ranieuwe Jul 10 '13 at 08:02
  • You could use the HTTPUtil.js program. Theres a screen cast that shows you how to use it http://channel9.msdn.com/Shows/Endpoint/endpointtv-Screencast-Building-RESTful-Services-with-WCF. Watch it from 11:30 onwards – beaumondo Jul 10 '13 at 08:15