How to Pass Parameters to WCF REST Service Method and Consuming in Website

Create WCF REST service.

Create ASP.NET website to consume service.

Step 1(Creating Service)

IService1.cs

  1. [ServiceContract]  
  2. public interface IService1   
  3. {  
  4.     [OperationContract]  
  5.     [WebInvoke(Method = "GET", UriTemplate = "Add/{num1}/{num2}")]  
  6.     string Add(string num1, string num2);  
  7. }  
  8. Service1.svc.cs  
  9. public string Add(string num1, string num2)   
  10. {  
  11.     int res = Convert.ToInt32(num1) + Convert.ToInt32(num2);  
  12.     return "Result is : " + res.ToString();  
  13. }
Step 2(Creating website)

Default.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html>  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.     <body>  
  9.         <form id="form1" runat="server">  
  10. Enter First Number      
  11.   
  12.             <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  13.             <br />  
  14. Enter Second Number  
  15.             <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  16.             <br />  
  17.             <asp:Button ID="btn_Add" runat="server" OnClick="btnAdd_Click" Text="Add" />  
  18.         </form>  
  19.     </body>  
  20. </html>
Default.aspx.cs

Note: Add these namespaces

 

  1. using System.Net;  
  2. using System.IO;  
  3. using System.Runtime.Serialization;  
  4. protected void btnAdd_Click(object sender, EventArgs e)   
  5. {  
  6.     WebClient proxy = new WebClient();  
  7.     byte[] abc = proxy.DownloadData((new Uri("http://localhost:21269/Service1.svc/Add/" + TextBox1.Text + "/" + TextBox2.Text)));  
  8.     Stream strm = new MemoryStream(abc);  
  9.     DataContractSerializer obj = new DataContractSerializer(typeof(string));  
  10.     string result = obj.ReadObject(strm).ToString();  
  11.     Response.Write(result);  
  12. }  

Thanks...