what are WCF REST services ?
Before going towards WCF REST service , we should know what is WCF service ?
simply Windows Communication Foundation (or WCF) is a runtime and a set of APIs (application programming interface) in the .NET Framework for building connected, service-oriented applications.It is designed using service-oriented architecture principles to support distributed computing where services have remote consumers.
For cross platform and inter programming language support basically two technologies can be used. SOAP and REST services.
Now going towards WCF REST service we are not able to call a WCF service method from HTTP protocal via Ajax call directly . Because using Ajax call can only call [WEBMETHOD] so for that we use REST service concept.
stands for
REST Representational State Transfer
.
The main idea behind REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to perform various operations on that resource.
When we talk about the Database as a resource we usually talk in terms of CRUD
operations
Now the basic CRUD operations are mapped to the HTTP protocols in the following manner:
- GET: This maps to the
R(Retrieve)
part of the CRUD operation. This will be used to retrieve the required data (representation of data) from the remote resource. - POST: This maps to the
U(Update)
part of the CRUD operation. This protocol will update the current representation of the data on the remote server. - PUT: This maps to the
C(Create)
part of the CRUD operation. This will create a new entry for the current data that is being sent to the server. - DELETE: This maps to the
D(Delete)
part of the CRUD operation. This will delete the specified data from the remote server.
The WCF part is composed of three files, the
- service contract
- service implementation
- app.config/Web.Config.
Step 1: Creat a WCF service Project from VS2010
Step-2 : Delete Existing by default Service from project and create new service
By three way we could create WCF REST Service.
1.) Using single Class
2.) Adding WCF Ajax call service
3.) Adding WCF service (2 & 3rd both are same but have different way to add in project)
service Interface "ILocaliteService.cs" where we only declare the methods .
using System.ServiceModel; using System.ServiceModel.Web; using Localite.Models; namespace localiteMobileService { [ServiceContract] public interface IlocaliteService { [OperationContract] [WebGet(UriTemplate = "GetProducts", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] string GetProducts(); [OperationContract] [WebGet(UriTemplate = "GetState({id})", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] string GetState(string id); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "AddProduct", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string AddProduct(string department, string student); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "Login", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string Login(string EmailAddress, string Password); } }
Now adding these attributes to these operations let us understand the concept of UriTemplate
.UriTemplate
is a property of WebGet and WebInvoke
attribute which will help us to map the parameter names coming from the HTTP protocol with the parameter names of ServiceContract
. For example, if someone uses the following URI:localhost/ILocaliteService/GetProducts
We need to map this first parameter with the id variable of the function. this can be done using the UriTemplate
. Also, we can change the function name specifically for the URI and the name of URI function name will be mapped to the actual function name i.e. if we need to call the same URL as:
localhost/localiteService/Products/2
then we can do that by specifying the UriTemplate
for the operation as:
[OperationContract] [WebGet(UriTemplate = "Products")] string GetProducts();
Implementing the Service
Now the service implementation part where we could use the entity framework generated context and entities to perform
the respective operations (CRUD)
using System.Collections.Generic; using System.ServiceModel.Activation; using Localite.Models; using Localite.Models.Repositories; namespace localiteMobileService { [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class localiteService : IlocaliteService { public string GetProducts() { return "success"; } public string GetState(string id) { return "success"; } public string AddProduct(string department, string student) { return "success"; } public string Login(string EmailAddress, string Password) { var accountService = new Localite.Controllers.AccountController(); var data = new Localite.Models.Repositories.UserRepository(); if (data.Authenticate(EmailAddress, Password)) { CurrentUserSession.UserInfo = data.GetUserByEmailID(EmailAddress); } return CurrentUserSession.UserInfo.ToString(); } } }
[AspNetCompatibilityRequirements(RequirementsMode= AspNetCompatibilityRequirementsMode.Allowed)] it will make our service class compatible to Asp.NET (only defined over class not on interface)Step-3 For successfull Execution of REST service we have to make some changes in WebConfig
As in my case i make changes shown there in the code .
Web.config
<?xml version="1.0" encoding="utf-8"?><configuration><system.web><compilation debug="true" targetFramework="4.0"><assemblies><add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies></compilation></system.web><system.serviceModel><behaviors><endpointBehaviors><behavior name="restfulBehavior"><webHttp /></behavior></endpointBehaviors><serviceBehaviors><behavior><serviceMetadata httpGetEnabled="true" /><serviceDebug includeExceptionDetailInFaults="false" /></behavior></serviceBehaviors></behaviors><services><service name="localiteMobileService.localiteService"><endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="" contract="localiteMobileService.IlocaliteService" /><endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" /><host><baseAddresses><add baseAddress="http://localhost/localiteService" /></baseAddresses></host></service></services><serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /><standardEndpoints><webHttpEndpoint><standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" /></webHttpEndpoint></standardEndpoints></system.serviceModel><system.webServer><modules runAllManagedModulesForAllRequests="true" /></system.webServer><connectionStrings><add name="LocaliteEntities" connectionString="metadata=res://*/Model.Localite.csdl|res://*/Model.Localite.ssdl|res://*/Model.Localite.msl;provider=System.Data.SqlClient;provider connection string="data source=Ws12;initial catalog=testLocalite;user id=dev;password=Password01*;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings></configuration>
Main Thing we need to add in Web.Config is
- Behaviours
1.) endpoint behaviour
2.) service behaviour
- Services
1.)Service
2.)endpoint
Step-4 : call REST service method from ajax
Demo.js
$(document).ready(function () { var host = "http://localhost:60895/"; var service = "localiteService.svc/"; $.ajax({ cache: false, type: "GET", async: false, url: host + service + "GetProducts", dataType: "json", success: function (student) { alert("success"); }, error: function (xhr) { alert("Error:" + xhr.responseText); } }); $("#login").click(function () { $.ajax({ cache: false, type: "POST", async: false, url: host + service + "Login", data: JSON.stringify(credentials), contentType: "application/json", dataType: "json", success: function (result) { alert(result); }, error: function (xhr) { alert(xhr.responseText); } }); }); });
By this way we can call a Web REST service from Ajax call. In case of creating WCF service by class we define both interface and service class in same .cs class file when we Add WCF service from AjaxEnable Service call we dont need to make changes in Web.config .Visual studio will do that for us and also give us sample interface declaration with [webInvoke() or WebGet()] In this article we have seen how we can create REST enabled WCF services. I hope this has been somewhat informative. :)