Click here to Skip to main content
15,878,852 members
Articles / WCF

WCF RESTful services and consuming them in an HTML page

Rate me:
Please Sign up or sign in to vote.
4.76/5 (11 votes)
1 Jul 2013CPOL6 min read 99.2K   3.7K   22   18
The article explains how to create a WCF RESTful service and consume it in a normal HTML page using a jQuery AJAX call.

Introduction

In this article I've discussed about WCF REST services and how to consume them in a normal HTML page. We will see what is required from a service developer's perspective to create a REST enabled WCF service. We see how we can use and consume RESTful WCF services.

Background

Overview of REST

REST stands for Representational State Transfer. This is a protocol for exchanging data over a distributed environment. 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.

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.

Walk through application

When you create a WCF service application project in Visual Studio you will get the IService1.cs and Service1.svc files along with a few other project related stuff. First we will discuss a few definitions which will be used in the article.

  • Operation Contract: The Operation Contract attribute is used to specify that the method is a web service method. Until unless you declare the attribute it will be treated as a normal method which can't be exposed to the outside world to consume it.
  • Data Contract: The Data Contract attribute is used to specify the class which contains properties, fields through which we store our business data and transmit our business data using web services to the clients who consumes them.
  • Data Member: The Data Member attribute is used with the properties or fields of a DataContract class. If you want this field data to be sent to the client it should be attributed as DataMember.
  • End Point: All communication with a Windows Communication Foundation (WCF) service occurs through the endpoints of the service. Endpoints provide clients access to the functionality offered by a WCF service.
  • Each endpoint consists of four properties:

    • An address that indicates where the endpoint can be found.
    • A binding that specifies how a client can communicate with the endpoint.
    • A contract that identifies the operations available.
    • A set of behaviors that specify local implementation details of the endpoint.
  • Binding: Bindings specify how a Windows Communication Foundation (WCF) service endpoint communicates with other endpoints.
  • Service Contract: A service contract describes the operation that a service provides. A Service can have more than one service contract but it should have at least one service contract.

A Service Contract can be defined using the [ServiceContract] and [OperationContract] attribute. The [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in a WebService.

Now we will see how to create two web service methods:

  • Method that returns the employee class instance as XML output.
  • Method that returns the employee class instance as JSON output.

In the code, I've created two entities:

  1. EmployeeXML class
  2. C#
    using System.Runtime.Serialization;
    
    namespace WcfServiceXmlAndJsonDemo
    {
        /// <summary>
        /// EmployeeXML class : This class is retrieved through servie
        /// as XML representation.
        /// </summary>
        [DataContract]
        public class EmployeeXML
        {
            #region Properties
    
            [DataMember]
            public string Name { get; set; }
    
            [DataMember]
            public int Id { get; set; }
    
            [DataMember]
            public double Salary { get; set; }
    
            #endregion
        }
    }
  3. EmployeeJSON class:
  4. C#
    namespace WcfServiceXmlAndJsonDemo
    {
        /// <summary>
        /// EmployeeJSON class : This class is retrieved through servie
        /// as JSON(JavaScript Object Notation) representation.
        /// </summary>
        [DataContract]
        public class EmployeeJSON
        {
            #region Properties
    
            [DataMember]
            public string Name { get; set; }
    
            [DataMember]
            public int Id { get; set; }
    
            [DataMember]
            public double Salary { get; set; }
    
            #endregion
        }
    }

The first method's return type is an instance of the EmployeeXML class and the other for the second method. Now I will show you how to expose our service methods to the clients.

Declare the two methods in the IService1 interface as follows:

[ServiceContract]
public interface IService1
{
    #region OperationContracts

    [OperationContract]
    [WebInvoke(Method="GET",UriTemplate="GetXml", 
      ResponseFormat=WebMessageFormat.Xml,RequestFormat=WebMessageFormat.Xml,
      BodyStyle=WebMessageBodyStyle.Bare)]
    EmployeeXML GetEmployeeXML();

    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "GetJson", 
      ResponseFormat = WebMessageFormat.Json, 
      RequestFormat = WebMessageFormat.Json, 
      BodyStyle = WebMessageBodyStyle.Wrapped)]
    EmployeeJSON GetEmployeeJSON();

    #endregion
}
  • Method="GET" specifies that it is the HTTP GET verb which performs the retrieval operation.
  • UriTemplate="GetXml" is the path through which the method is accessed (http://localhost/Service1.svc/GetXml).
  • ResponseFormat specifies the response format of the method and RequestFormat is the way you should send data if any parameters are present for the method to request any data.

Now implement the methods in the Service1.svc file as follows:

public class Service1 : IService1
{
    #region ImplementedMethods

    public EmployeeXML GetEmployeeXML()
    {
        EmployeeXML xml = new EmployeeXML() {Name="Sudheer",Id=100,Salary=4000.00 };
        return xml; ;
    }

    public EmployeeJSON GetEmployeeJSON()
    {
        EmployeeJSON json = new EmployeeJSON() {Name="Sumanth",Id=101,Salary=5000.00 };
        return json;
    }

    #endregion
}

The next important thing is the Web.config file which is the key part of the service. In web.config you should specify the service metadata, that is, the details of binding and the endpoint through which the clients can access your service. The important things to consider in web.config file are:

  1. Service behavior.
  2. End point behavior.
XML
<system.servicemodel>
    <behaviors>
      <servicebehaviors>
        <behavior>
          <servicemetadata httpsgetenabled="true" httpgetenabled="true">
          <servicedebug includeexceptiondetailinfaults="false">
        </servicedebug> </servicemetadata></behavior>
      </servicebehaviors>
    <endpointbehaviors>
      <behavior name="web">
        <webhttp>
      </webhttp></behavior>
    </endpointbehaviors>
    </behaviors>
    <protocolmapping>
        <add scheme="https" binding="basicHttpsBinding">
    </add></protocolmapping>    
    <servicehostingenvironment multiplesitebindingsenabled="true" aspnetcompatibilityenabled="true">
  <services>
    <service name="WcfServiceXmlAndJsonDemo.Service1">
      <endpoint binding="webHttpBinding" 
        contract="WcfServiceXmlAndJsonDemo.IService1" behaviorconfiguration="web">
    </endpoint> </service>
  </services>
  </servicehostingenvironment>
</system.servicemodel>

Testing the Service

Now right click on the Service1.svc file and select the View in browser option as follows:

Image 1

Now your browser looks something like this:

Image 2

Now add the uritemplate of the method to see the output. Ex: localhost:1249/Service1.svc/GetXml gives you the following output:

Image 3

The same way you can also see the JSON output by adding the uritemplate specific to the JSON method (GetJson). Following is the JSON output:

Image 4

Client application to consume the WCF service

Now go ahead and create an empty web application and add an HTML page with the following code. Note: Don't forget to add the jQuery library to the application as we are going to consume the WCF service using a jQuery AJAX call. The HTML code for the page is as follows (part of the code, for full code please go through the code I've attached):

JavaScript
<script>
    $(document).ready(function () {    
    });
    var GetJson = function () {
        $.ajax({
            type: "GET",
            url: "http://localhost:4545/Service/Service1.svc/GetJson",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (data) {
                var result = data.GetEmployeeJSONResult;
                var id = result.Id;
                var name = result.Name;
                var salary = result.Salary;
                $('#jsonData').html('');
                $('#jsonData').append('<table border="1"><tbody><tr><th>" + 
                  "Employee Id</th><th>Name</th><th>Salary</th>" + 
                  "</tr><tr><td>' + id + '</td><td>' + name + 
                  '</td><td>' + salary + '</td></tr></tbody></table>');

            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
    }
    var GetXml = function () {
        $.ajax({
            type: "GET",
            url: "http://localhost:4545/Service/Service1.svc/GetXml",
            dataType: "xml",
            success: function (xml) {
                $(xml).find('EmployeeXML').each(function () {
                    var id = $(this).find('Id').text();
                    var name = $(this).find('Name').text();
                    var salary = $(this).find('Salary').text();
                    $('#xmlData').html('');
                    $('#xmlData').append('<table border="1"><tbody><tr><th>Employee" + 
                      " Id</th><th>Name</th><th>Salary</th></tr><tr><td>' + 
                      id + '</td><td>' + name + '</td><td>' + salary + 
                      '</td></tr></tbody></table>');
                });
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
    }
</script>

The URL I've provided above is already published and hosted in IIS. It may vary from yours. So please look through the below steps for how to host the application under IIS.

Now we are ready with the code side. The next big part is hosting your service and client application in IIS in the same port. Why I've have specified the same port is because of the WCF service account's cross domain issues i.e., the client application should run under the same port that the service runs.

Hosting the application in IIS

Step 1: Publish your application by right clicking the project and selecting the Publish option as follows:

Publishing the Service

Image 5

Image 6

Image 7

Image 8

Image 9

Publishing the Client

Image 10

Image 11

Image 12

Image 13

Note: Publish both the client and service application in the same parent folder.

Image 14

Step 2: Add a new website under IIS and map that physically to the application parent folder as follows:

Image 15

Be cautious while adding the dite name because while typing the name it will also be reflected in the application pool as follows:

Image 16

Image 17

Image 18

Image 19

Image 20

Image 21

Now you can run your client application and you will see the following output:

Caution: You will get the following error:

Image 22

Now go back to IIS and select Client and choose the following:

Image 23

Image 24

Image 25

Image 26

Image 27

Image 28

Hope you will find this helpful.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionThank you...very helpful Pin
Member 856297924-Aug-16 7:54
Member 856297924-Aug-16 7:54 
QuestionWhile running "http://localhost:1762/Service1.svc/GetJSON or GetXML" shows blank page. Pin
Member 1112533515-Jun-16 2:06
Member 1112533515-Jun-16 2:06 
QuestionMessage Closed Pin
27-Jan-15 0:47
professionalSid_Joshi27-Jan-15 0:47 
AnswerRe: How to pass Parameters in GetXml Pin
Sudheer Reddy K27-Jan-15 0:59
Sudheer Reddy K27-Jan-15 0:59 
GeneralRe: How to pass Parameters in GetXml Pin
Sid_Joshi27-Jan-15 1:06
professionalSid_Joshi27-Jan-15 1:06 
QuestionYour code returns null Pin
M_0325-Aug-14 20:30
professionalM_0325-Aug-14 20:30 
AnswerRe: Your code returns null Pin
Sudheer Reddy K6-Dec-14 17:59
Sudheer Reddy K6-Dec-14 17:59 
QuestionGetJSON return This page can’t be displayed !! Pin
badarhn24-Dec-13 6:38
badarhn24-Dec-13 6:38 
QuestionI am Beginner for WCF Web service ... Pin
Gurunathan301017-Sep-13 20:42
Gurunathan301017-Sep-13 20:42 
AnswerRe: I am Beginner for WCF Web service ... Pin
Gurunathan301017-Sep-13 22:12
Gurunathan301017-Sep-13 22:12 
AnswerRe: I am Beginner for WCF Web service ... Pin
Sudheer Reddy K3-Oct-13 18:54
Sudheer Reddy K3-Oct-13 18:54 
QuestionRest WCF Service in Windows service hosting Pin
RamanIndia12-Sep-13 21:32
RamanIndia12-Sep-13 21:32 
AnswerRe: Rest WCF Service in Windows service hosting Pin
Sudheer Reddy K12-Sep-13 22:15
Sudheer Reddy K12-Sep-13 22:15 
QuestionVery good article and its well written! Pin
Ganesh_d117-Jul-13 22:49
Ganesh_d117-Jul-13 22:49 
AnswerRe: Very good article and its well written! Pin
Sudheer Reddy K17-Jul-13 22:56
Sudheer Reddy K17-Jul-13 22:56 
QuestionTwo entities are necessary? Pin
Holger S. Germany1-Jul-13 1:12
Holger S. Germany1-Jul-13 1:12 
AnswerRe: Two entities are necessary? Pin
Sudheer Reddy K1-Jul-13 1:20
Sudheer Reddy K1-Jul-13 1:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.