Click here to Skip to main content
13,139,569 members (54,179 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

70.2K views
3.4K downloads
19 bookmarked
Posted 29 Jun 2013

WCF RESTful services and consuming them in an HTML page

, 1 Jul 2013
Rate this:
Please Sign up or sign in to vote.
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. 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. 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.
<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:

Now your browser looks something like this:

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

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:

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):

<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

Publishing the Client

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

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

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

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

Caution: You will get the following error:

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

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)

Share

About the Author


You may also be interested in...

Pro

Comments and Discussions

 
QuestionThank you...very helpful Pin
Member 856297924-Aug-16 7:54
memberMember 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
memberMember 1112533515-Jun-16 2:06 
AnswerRe: How to pass Parameters in GetXml Pin
Sudheer Reddy K27-Jan-15 0:59
memberSudheer Reddy K27-Jan-15 0:59 
GeneralRe: How to pass Parameters in GetXml Pin
8838813227-Jan-15 1:06
professional8838813227-Jan-15 1:06 
QuestionYour code returns null Pin
monika0325-Aug-14 20:30
membermonika0325-Aug-14 20:30 
AnswerRe: Your code returns null Pin
Sudheer Reddy K6-Dec-14 17:59
professionalSudheer Reddy K6-Dec-14 17:59 
SuggestionMessage Closed Pin
6-Mar-14 1:57
professionalRavi.Kumar0216-Mar-14 1:57 
QuestionGetJSON return This page can’t be displayed !! Pin
badarhn24-Dec-13 6:38
memberbadarhn24-Dec-13 6:38 
QuestionI am Beginner for WCF Web service ... Pin
Gurunathan301017-Sep-13 20:42
memberGurunathan301017-Sep-13 20:42 
AnswerRe: I am Beginner for WCF Web service ... Pin
Gurunathan301017-Sep-13 22:12
memberGurunathan301017-Sep-13 22:12 
AnswerRe: I am Beginner for WCF Web service ... Pin
Sudheer Reddy K3-Oct-13 18:54
professionalSudheer Reddy K3-Oct-13 18:54 
QuestionRest WCF Service in Windows service hosting Pin
RamanIndia12-Sep-13 21:32
memberRamanIndia12-Sep-13 21:32 
AnswerRe: Rest WCF Service in Windows service hosting Pin
Sudheer Reddy K12-Sep-13 22:15
professionalSudheer Reddy K12-Sep-13 22:15 
QuestionVery good article and its well written! Pin
ganesh_d117-Jul-13 22:49
memberganesh_d117-Jul-13 22:49 
AnswerRe: Very good article and its well written! Pin
Sudheer Reddy K17-Jul-13 22:56
professionalSudheer Reddy K17-Jul-13 22:56 
QuestionTwo entities are necessary? Pin
Holger S. Germany1-Jul-13 1:12
memberHolger S. Germany1-Jul-13 1:12 
AnswerRe: Two entities are necessary? Pin
Sudheer Reddy K1-Jul-13 1:20
professionalSudheer 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170915.1 | Last Updated 1 Jul 2013
Article Copyright 2013 by Sudheer Reddy K
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid