Click here to Skip to main content
15,112,662 members
Articles / Programming Languages / C#
Posted 21 Jan 2011

Tagged as


80 bookmarked

.NET 4.0 RESTful Web Service Introduction

Rate me:
Please Sign up or sign in to vote.
4.74/5 (22 votes)
21 Jan 2011CPOL6 min read
Introduces you to the basics of RESTful Web Services.

REST - REpresentational State Transfer

REST is not a standard but an approach (specification) to developing and providing services on the internet. REST follows an architectural style of web application, like a user progressing through a web application by selecting links which takes him to the next page. REST is based on Resources that are identified by a unique URI.

When we conform to the standard or characteristic defined for a service to be REST, we can refer the service to be RESTful. REST does not tie itself to any particular platform, but is currently done on Web with HTTP.

Fundamental Characteristics / Constraints of REST

Client Server

Separation of Concerns is a principle where the user interface is separated from data storage. This leads to the portability of the user interface across multiple platforms and improves scalability by simplifying server components.


Each request to the server should contain all the information required to understand and complete the request.


The data within a response to a request should be cacheable/ non-cacheable to be used by client at another point of time. This might improve the performance and reduce network traffic.

Layered System

Intermediary servers like Proxy servers or Cache servers can be used to improve performance or introduce security.

Uniform Interface

A uniform interface (like HTTP GET, POST, DELETE, PUT) is to be used to access a resource.

A RESTful Web Service is a collection of the following:


Uniform Resource Identifier - This is a unique way of identifying resources on the network. Every resource on the web is given a unique identifier - a universal identifier (example, URL). All web browsers, servers, applications understand this identifier, which makes it easy to connect and exchange information between one another without any issues.


Can be XML, HTML, and JSON.

HTTP Methods

HTTP forms a standard way to communicate with resources on the web. GET, PUT, DELETE, POST are some of the common methods to access a resource.


Helps to request a specific representation of the resource.


Updates a resource with a specific representation.


Deletes a specified resource.


Creates a new resource.

Designing RESTful Services

The initial steps in designing RESTful based services is to identify the objects (resources) that will be exposed to the outside world and next to map these resources to a URI. We should not focus on designing the methods for an application; instead, we should focus on designing resources and their URI. There are various data formats which can be used with REST, but XML is easier and mostly used, but JSON is equally being used.

.NET 4 and REST and WCF

WCF is not all about building SOAP based services, it's an extensible framework with a common programming model and a totally pluggable communication infrastructure. The basic job of the WCF runtime is to listen for messages from a network location and process those messages and pass them to the application (service). With .NET 4, developing a REST application is an easy task. Microsoft has provided a REST template which we can use to create new projects, this will create a basic skeleton code for REST.

From VS 2010, create a new project, select an online template, and WCF. There are various options displayed, select "WCF REST Service Template 40".

Create a class which returns a collection of employee details. Mark the method which we want to call with the attribute [WebGet()].

[AspNetCompatibilityRequirements(RequirementsMode = 
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 
// NOTE: If the service is renamed, remember to update the global.asax.cs file 
public class Service1
    // TODO: Implement the collection resource
    // that will contain the SampleItem instances 
    [WebGet(UriTemplate = "")] 
    public IList<EmployeeDetail> GetEmployeeDetail() 
        IList<EmployeeDetail> employeeDetail = 
                          new List<EmployeeDetail>(); 
        EmployeeDetail empDetail1 = new EmployeeDetail(); 
        empDetail1.EmployeeIdentifier = 123; 
        empDetail1.EmployeeName = "Test1"; 
        empDetail1.ProjectName = "NE"; 
        EmployeeDetail empDetail2 = new EmployeeDetail(); 
        empDetail2.EmployeeIdentifier = 1234; 
        empDetail2.EmployeeName = "Test2"; 
        empDetail2.ProjectName = "NE"; 
        return employeeDetail; 

public class EmployeeDetail 
    private string employeeName; 
    private int employeeId; 
    private string projectName; 
    public int EmployeeIdentifier
            return employeeId; 
            employeeId = value; 

    public string EmployeeName 
            return employeeName; 
            employeeName = value; 
    public string ProjectName 
            return projectName; 
            projectName = value; 

Build and run the code. Now access the URL http://localhost:8422/Service1/. The following XML is returned from the service:

<ArrayOfEmployeeDetail xmlns="" 

Security and REST

If you look into the above code, you will noticed the flaw, this service does not have any security aspect built into it. But when we are building services exposing endpoints, the security aspect should be taken care of. RESTful services are just HTTP endpoints, so all security aspects implemented with HTTP (like HTTPS, certificates) can also be implemented with REST.

There are two types of hosting services, self hosting Web Services and Web Services hosted with an application server like IIS. In self hosting Web Services, most of the security aspect should be taken care of in the code; on the other hand, while hosted in IIS, the setting in IIS take care of the security.

Setting Endpoint: Security for Self Hosted

Security of the end point is set by the Security property of WebHttpBinding. The Security property is of type WebHttpSecurity and is used to determine the security mode required by the binding and the type of client credentials it requires. There are two properties of WebHttpSecurity: Mode (of type WebSecurityHttpMode) and Transport (of type HttpTransportSecurity). There are three levels of security that can be specified using WebHttpSecurityMode:

  1. None
  2. Transport
  3. TransportCredentialOnly

WebHttpBinding.Security.Transport which is of type HttpTransportSecurity helps to authenticate the client. It has these three properties:

  • ClientCredentialType (of type HttpClientCredentialType)
  • ProxyCredentialType (of type HttpProxyCredentialType)
  • Releam (String)

Values for HttpClientCredentialType can be any one of the following: None, Basic, Digest, NTLM, Windows, Certificate.

Setting Endpoint: Security for Services Deployed on IIS

When hosting an endpoint on IIS, use the web.config file to make configuration changes. The configuration can be done for the virtual directory where the service is running. We need to be aware of both the client config and the virtual directory configuration.


Once authenticated, the next step is to authorize the client, what they can do and what they can't do.

  1. Impersonation: by impersonating the client, the authorization is delegated to another layer. For example, when a client is trying to insert or update data in to a SQL Server database, SQL Server throws an exception in case the client doesn't have permission, which can be bubbled back to the client.
  2. Role based: Implement authorization by restricting access to operations to certain Windows users or groups.

Advantages of REST

  • Services offered by REST style are easier to consume compared to other style services, meaning lower learning curve for the consumer.
  • Supports caching of URI of the service.
  • Components can be deployed independently.
  • Lightweight (consider SOAP which uses WSDL which makes the SOAP protocol a complex service).
  • Simple clients.

Disadvantage of REST

The major disadvantage from a developer's perceptive is it does not have metadata. So it requires knowledge of implementation details. On the security aspect, RESTful services depend on the security aspect of HTTP security.

When to Use REST

REST can be implemented when we plan to design an application to be used exclusively on the web, and also when we need a quick client integration.

When Not to Use REST

When designing an application of service oriented architecture which interconnects many systems and uses many transport channels, it is better to use SOAP.


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


About the Author

United States United States
No Biography provided

Comments and Discussions

QuestionUnittesting the service Pin
Gauri Chodanker23-Dec-14 21:52
MemberGauri Chodanker23-Dec-14 21:52 
Please advise if there is any tool to unittest this service.
QuestionSecurity For REST Pin
Khanh Nguyen28-Sep-14 16:20
MemberKhanh Nguyen28-Sep-14 16:20 
GeneralMy vote of 3 Pin
anupam jaiswal24-Nov-12 9:51
Memberanupam jaiswal24-Nov-12 9:51 
Questionadvantages compares to standard Web service Pin
SaurabhSavaliya30-Apr-12 3:14
MemberSaurabhSavaliya30-Apr-12 3:14 
QuestionGood introductory article on Restful Service Pin
Rupesh Kumar Tiwari20-Oct-11 6:08
MemberRupesh Kumar Tiwari20-Oct-11 6:08 
GeneralMy vote of 5 Pin
eiiov_gr819-Oct-11 4:23
Membereiiov_gr819-Oct-11 4:23 
QuestionPlease do an article on how to deploy to IIS Pin
chispnw30-Jun-11 12:54
Memberchispnw30-Jun-11 12:54 
AnswerRe: Please do an article on how to deploy to IIS Pin
chispnw30-Jun-11 13:26
Memberchispnw30-Jun-11 13:26 
GeneralRequest Body Pin
LuisR119-Apr-11 9:00
MemberLuisR119-Apr-11 9:00 
GeneralI did a RESTful one a while back that may be of interest Pin
Sacha Barber21-Jan-11 4:08
mvaSacha Barber21-Jan-11 4:08 

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.