Although ASP.NET Web API replaces Windows Communication Foundation (WCF) Services, the later still remains one of the most widely used frameworks for building service-oriented applications. In most enterprise apps, WCF Services are used as an interface for distributing business logic across various client applications. During the beginning, the communication support provided by WCF was restricted to HTTP, TCP, and MSMQ protocols. With increasing popularity and adoption of REpresential State Transfer (REST), WCF 3.5 enabled REST via the WebGet and WebInvoke attributes and the WebHttpBinding. This allowed you to expose a ServiceContract as a REST service which can be invoked using either JSON or plain XML.
JavaScript Object Notation (JSON) is now a popular format for data communication across variety of clients ranging from browser client to device clients. In this article, we will consume WCF REST Service in ASP.NET MVC client using the popular JavaScript MVC framework called Angular.js.
Note: The following steps will guide you through the procedure of accessing WCF REST Service using Angular.js. These steps can be extended as per your project requirements.
Step 1: Open Visual Studio 2013 (the current application is developed using VS2013 Ultimate with Update 3), create a new blank solution, and name it as ‘A7_Consuming_WCF_REST_In_Angular’.
Step 2: In this solution, add a new WCF Service Application and call it ‘WCF_DataService’. In this project, add a new App_Data folder.Now add a new Sql Server Database called ‘Application.mdf’. In this database, add a new table ‘Employee’ with the following definition:
CREATE TABLE [dbo].[Employee] (
[EmpNo] INT IDENTITY (1, 1) NOT NULL,
[EmpName] VARCHAR (100) NOT NULL,
[Salary] INT NOT NULL,
[DeptName] VARCHAR (50) NOT NULL,
[Designation] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([EmpNo] ASC)
);
Step 3: In the project, add a new folder with the name ‘Models’. In this project, add a new ADO.NET Entity Data Model and call it ‘ApplicationEDMX’. Select the Database First approach of EntityFramework. Complete the Wizard by selecting Application.mdf as database and Employee as table. After completing the Wizard the table mapping will be as follows:
Step 4: In the project, rename the IService1.cs to IService.cs and Service1.svc to Service.Svc. Open IService.cs and replace the default code:
using System.ServiceModel;
using System.ServiceModel.Web;
using WCF_DataService.Models;
namespace WCF_DataService
{
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet(UriTemplate="Employees",ResponseFormat=WebMessageFormat.Json)]
Employee[] GetEmployees();
}
}
The above ServiceContract has an OperationContract of the name GetEmployees(). This is applied with the attribute WebGet which represents the behavior of the OperationContract for logically retrieving the data in WCF REST Service. This attribute is set with the UriTemplate property, using which the template for the OperationContract can be set while accessing it. The ResponseFormat property specifies the format of the data retrieved from the method. The current value is JSON.
Step 5: Right-click on the Service.svc and select ‘View Markup’. This will open the Service hosting markup and add the new ‘Factory’ attribute for the WCF REST as shown here:
<%@ ServiceHost Language="C#" Debug="true" Service="WCF_DataService.Service" CodeBehind="Service.svc.cs"
Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>
Step 6: Open Service.svc.cs and replace the default code using the following code:
using System.Linq;
using WCF_DataService.Models;
namespace WCF_DataService
{
public class Service : IService
{
ApplicationEntities ctx;
public Service()
{
ctx = new ApplicationEntities();
}
/// <summary>
/// Method retrieves Employees using
/// ADO.NET EF
/// </summary>
/// <returns></returns>
public Employee[] GetEmployees()
{
return ctx.Employees.ToArray();
}
}
}
The above code shows the implementation of the ServiceContract IService and its GetEmployees() OperationContract. This retrieves Employees using EntityFramework.
Step 7: Open Web.Config file and change the protocolMapping to webHttpBinding instead of basicHttpsBinding. This will enable the WCF service for REST. Also add the endpointBehaviors under behavior for help page so that when the Service is accessed through the browser, it will show the URL to access the OperationContract.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp helpEnabled="True"/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Step 8: View the Service in the Browser by right clicking on Service.svc. The browser will show the result as below:
Click on the service help page , which will show the url description to access the OperationContract as shown here:
The URL can be tested as shown here (for the sake of simplicity, I have tested it in the chrome)
The above screenshot shows the Data retrieved from the WCF REST Service in JSON format. Host the Service in IIS for easy access. The process of hosting WCF Service in IIS is explained in this article.
Defining our ASP.NET MVC application
Step 9: In the same solution, add a new empty ASP.NET MVC application and name it as Angular Client. In this project, add references for Angular.js using Manage NuGet Package.
Step 10: In the scripts folder, add a new folder of the name MyScripts and put the following JavaScript files:
Modules.js
/// <reference path="../angular.min.js" />
var app;
(function () {
app = angular.module("RESTClientModule", []);
})();
The above JavaScript defines Angular Module with the name RESTClientModule. This is the Bootstrapper for the application.
Services.js
/// <reference path="../angular.min.js" />
/// <reference path="Modules.js" />
app.service("RESTClientService", function ($http) {
this.get = function () {
return $http.get("http://localhost:8020/WCFApp/Service.svc/Employees");
};
});
The above JavaScript code define the Angular Service of name RESTClientService in the Angular module. This makes use of $http to make call to the WCF REST service.
Controllers.js
/// <reference path="../angular.min.js" />
/// <reference path="Modules.js" />
/// <reference path="Services.js" />
app.controller("RESTClientController", function ($scope, RESTClientService) {
// debugger;
var promiseGet = RESTClientService.get();
promiseGet.then(function (pl) {
$scope.Employees = pl.data
},
function (errorPl) {
$log.error('failure loading Employee', errorPl);
});
});
The above JavaScript code defines Angular Controller on the Module which defines $scope to be bound with the UI. The controller has the dependency on the RESTClientService so that the controller can make call methods from the service. The controller makes use of the Promise object to manage an Asynchronous calls to the method ‘GET’ method from the service. Once the call is complete, the retrieved data will be stored in the $scope.Employees which will be used for DataBinding in the UI.
Step 11: In MVC project, add a new empty MVC controller with the name MVCWCFClientController. This will contain the Index action method. Add a new Empty View in the MVC using scaffolding (right-click on the Index methods and select Add View). In the Index.cshtml add the <table> with DataBinding as here:
<html ng-app="RESTClientModule">
<style type="text/css">
table, td {
border: double;
}
thead {
background-color:darkgray;
font-size:20px;
font-family:Courier New, Courier, monospace;
font-weight:900;
}
</style>
<h2>Consuming WCF REST Service in Angular JS</h2>
<body>
<table ng-controller="RESTClientController">
<tr>
<td>
<table>
<thead>
<tr>
<td>EmpNo</td>
<td>EmpName</td>
<td>Salary</td>
<td>DeptName</td>
<td>Designation</td>
</tr>
</thead>
<tbody ng-repeat="Emp in Employees">
<tr>
<td> <span>{{Emp.EmpNo}}</span></td>
<td> <span>{{Emp.EmpName}}</span></td>
<td> <span>{{Emp.Salary}}</span></td>
<td> <span>{{Emp.DeptName}}</span></td>
<td> <span>{{Emp.Designation}}</span></td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</body>
</html>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/MyScripts/Modules.js"></script>
<script src="~/Scripts/MyScripts/Services.js"></script>
<script src="~/Scripts/MyScripts/Controllers.js"></script>
In the above HTML code, the Angular binding is done using the following directives:
- ng-app – bound with Module for the bootstrapping
- ng-controller – bound with the Controller, so that the $scope declared in the controller can be bound with the UI.
- ng-repeat - This is an iteration for $scope.Employees so that the data from it can be shown in Table.
Run the application, the result will be as below:
Conclusion
WCF REST has provides benefits of retrieving data in an Open format like JSON, using which it can be consumed by the various categories of client applications. AngularJS provides a simplified approach of accessing WCF REST service for managing Business Logic and Data Access in enterprise applications.
Download the entire source code of this article (Github)
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn