Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume WCF REST Service in C#?

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);
like image 963
senthil kumar Avatar asked Jul 10 '13 07:07

senthil kumar


People also ask

How do you consume WCF service?

Consuming WCF Service Now right click on WCFClient project select "Add Service Reference" and paste copied URL in Address section of "Add Service Reference" dialog box and click on Go button and rename Namespace as "UserService" and click ok button.

Is it possible to use WCF as RESTful services?

You can use WCF to build RESTful services in . NET. REST (Representational State Transfer) is an architecture paradigm that conforms to the REST architecture principles. The REST architecture is based on the concept of resources: It uses resources to represent the state and functionality of an application.

How can I call WCF service using Postman?

If you want to call a remote WCF service from Postman (that you can't run locally), debug your local project, so the WCF Test Client opens. 1.) Right-click on the 'My Service Projects' tree node in WCF Test Client, and click 'Add Service'.


2 Answers

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;
like image 144
Amit Avatar answered Sep 17 '22 13:09

Amit


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);
    }
like image 38
Prateek Gupta Avatar answered Sep 18 '22 13:09

Prateek Gupta