Objective
This article will give a quick walkthrough on how to consume a WCF REST Service in ASP.Net Web site.
1. Create a WCF REST Service.
2. Consume the Service in ASP.Net Web Site
Create a WCF REST Service
Step 1
Create a WCF application. To create a new application File -> New -> Web-> WCF Service Application.
Step 2
Remove all the default code created by WCF. Remove code from IService 1 interface and Service1 class. Remove the code from Web.Config also. Open Web.Config and remove System.Servicemodel codes.
Step 3
Right click on Service1.svc select View markup and add below code
<%@ ServiceHost Language=”C#” Debug=”true” Service=”FetchingImageinBrowser.Service1″ CodeBehind=”Service1.svc.cs” Factory=”System.ServiceModel.Activation.WebServiceHostFactory” %>
Step 4
Create contract. Operation contract will return Stream. Stream is in the namespace System.IO. By putting WebGet attribute make operation contract
IService1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Web;
namespace WcfService6
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate="/GetData")]
string GetData();
}
}
Step 5
Implement the service
Service1.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService6
{
public class Service1 : IService1
{
public string GetData()
{
return "hello From REST ";
}
}
}
Press F5 to run the service
Consume the Service in ASP.Net Web Site
Step 1
Create an ASP.Net Web Site. Navigate to File -> New -> Web Site
Step 2
Drag and drop one button and text box on the page.
Step 3
Add the namespace of
System.RunTIme.Serilization
System.Net
System.IO
Step 4
On the click event of the button,
In above code,
1. Create instance of WebClient class.
2. Down load the data in byte array form.
3. Create the stream from byte array
4. Using Data Contract Serializer deserialize the stream.
5. Get the result in string
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Net;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
WebClient proxy = new WebClient();
byte[] abc = proxy.DownloadData((new Uri("http://localhost:4567/Service1.svc/GetData")));
Stream strm = new MemoryStream(abc);
DataContractSerializer obj = new DataContractSerializer(typeof(string));
string result = obj.ReadObject(strm).ToString();
TextBox1.Text = result;
}
}
Run to get the output.
Leave a Reply