In this blog post, you will learn how to consume the WCF REST service in the C# ASP.Net web application. Previously I have explained how to create WCF REST Service in C# and Exception Handling in WCF using Fault Contract. You can follow the below steps to calling WCF rest service:-
- First of all, you need to host WCF restful service somewhere on the webserver or at IIS on the local machine. In my example the URL of that XML Service: http://localhost:63663/Service1.svc/GetCustomerListXML, and JSON Service: http://localhost:63663/Service1.svc/GetCustomerListJSON.
- Now, right-click on the project and select Add -> Service Reference as shown below:-
- Paste the wcf rest service URL (http://localhost:63663/Service1.svc) and click on the Go button to see a list of available services as shown below. All your available web methods (services) will appear on the pane below. Give specific reference namespace. Here I am giving the referenced namespace as “ServiceReference1”. Click on the Ok button to finish the Add service reference Wizard.

- After clicking on the Ok button a service model will generate in your web.config file as follows.

Now, find the below source code to consume wcf rest service c# json and XML format.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Consume_Wcf_Rest_Service.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <h3>From JSON Response</h3> <asp:GridView ID="grdDisplayJSON" runat="server"> </asp:GridView> <br /> <br /> <h3>From XML Response</h3> <asp:GridView ID="grdDisplayXML" runat="server"> </asp:GridView> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; using System.Web.UI; using System.Web.UI.WebControls; namespace Consume_Wcf_Rest_Service { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { ServiceReference1.Service1Client proxyClient = new ServiceReference1.Service1Client(); JavaScriptSerializer js = new JavaScriptSerializer(); object jsonResult = proxyClient.GetCustomerListJSON(); string strJSON = js.Serialize(jsonResult); // Converting object to JSON format string grdDisplayJSON.DataSource = jsonResult; grdDisplayJSON.DataBind(); object xmlResult = proxyClient.GetCustomerListXML(); grdDisplayXML.DataSource = xmlResult; grdDisplayXML.DataBind(); } } catch (Exception ex) { throw ex; } } } }
Output

Conclusion
I hope you liked this article on Consume Wcf Rest Service in C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Leave a Reply