Implementing a WCF service based on REST and JSON


In this article we are going to see how to write a WCF Service Based on REST and JSON. Implementing a WCF service based on REST and JSON is easy in ASP.NET because of the AJAX support built into ASP.NET. In Visual Studio, There is a WCF template which can be used to create a service that takes advantage of REST calling mechanism and JSON data format.

Implementing a WCF service based on REST and JSON is easy in ASP.NET because of the AJAX support built into ASP.NET. In Visual Studio, There is a WCF template which can be used to create a service that takes advantage of REST calling mechanism and JSON data format.

The AJAX-Enabled WCF Service template defines a class that can be used to create a WCF service for use with AJAX.
For example, Let us create a service to display the Employee salary based on the EmployeeId.

Step 1: Open Visual Studio and Create a ASP.NET website and name it as "MyEmpSite" as shown below:
ws
Step 2: Now add "AJAX-Enabled WCF service" to the website. Right click on "MyEmpSite" and Add New Item. Select "AJAX-Enabled WCF service" template and name it as EmpService.svc as shown below:
wcf
When the AJAX enabled WCF service is added to the site,Visual Studio updates the Web.config file. Observe the following configuration file section. Notice the element. This indicates that the endpoint is a RESTful service that uses the JSON data format and can
thus be consumed by AJAX. Here webHttpBinding binding is used, indicating
again that this service is called via HTTP.

binding

Step 3: Write the code shown below in this service.


namespace EmpServices
{
[ServiceContract(Namespace = "EmpServices")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EmpService
{
[OperationContract]
[WebInvoke]
public double GetEmpSalary(int empId)
{
//You can write the code to get the data from database.
//For simplicity I wrote switch case here.

switch (empId)
{
case 1: return 3000;
case 2: return 5000;
case 3: return 45000;
}
//If the empId is not matching throw an error.
throw new ApplicationException("No data");
}
}
}

Here we have written "EmpService" class in the EmpServices namespace. In this class we have the method "GetEmpSalary". The service method is marked with the WebInvoke attribute. This indicates that the method can be called by an HTTP request using HTTP POST.

Step 4: Calling a JSON-Based WCF Service from AJAX:
Add a ScriptManager control to your page. In the ScriptManager control, set a service reference to the RESTful WCF service "EmpService.svc". Doing this will define a JavaScript proxy class for you to call. This
proxy class manages the call from the AJAX-enabled page to the WCF service(EmpService.svc). Following is the code.

<asp:ScriptManager id="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="EmpService.svc" />
</Services>
</asp:ScriptManager>





Step 5:Update the web.config file as shown below to include the EmpServices namespace in the service configuration:

<services>
<service name="EmpServices.EmpService">
<endpoint address="" behaviorConfiguration="EmpServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="EmpServices.EmpService" />
</service>
</services>

Step 6: Write the below code in Default.aspx page:

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script language="javascript" type="text/javascript">
function GetEmpSalary() {
var service = new EmpServices.EmpService();
service.GetEmpSalary(document.forms[0].MainContent_txtEmpId.value, onSuccess, onFail, null);
}

function onSuccess(result) {
MainContent_lblSalary.innerText = result;
}

function onFail(result) {
alert('No Data');
}
</script>
</asp:Content>

In the above code, we create an instance of the EmpService service and call the "GetEmpSalary" method of the service. Notice that this method accepts below parameters:
1.The value entered by the user in the "txtEmpId" textbox.
2.The reference to the JavaScript method "onSuccess". This method is called by the ScriptManager after the service is called and success is returned. Here, a successful call writes the results to a Label control.
3.The reference to the JavaScript method "onFail". This method is called by the ScriptManager after the service is called and the call fails due to some error.
Now define a script block on your page to call the proxy class that is generated based on the above service reference. In our example, the service takes an Employee ID.

Step 7: Now add the below code to the Default.aspx page:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
Emp Id: <asp:TextBox runat="server" ID="txtEmpId"></asp:TextBox>
<input name="btnGetSalary" type="button" value="Get Salary" onclick="GetEmpSalary()" />
<asp:Label runat="server" ID="lblSalary"></asp:Label>
</asp:Content>

In the above code we have added few controls. When the user enters a value in the textbox (txtEmpId) and clicks the button "btnGetSalary", It calls the method : "GetEmpSalary()". this method call the service method and if the call is successful, it calls the onSuccess Javascript method else it calls the onFail Javascript method if the call fails.


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: