Click here to Skip to main content
Click here to Skip to main content
Go to top

.NET 4.0 RESTful Web Service Introduction

, 21 Jan 2011
Rate this:
Please Sign up or sign in to vote.
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.

Stateless

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

Cacheable

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:

URI

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.

MIME Type

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.

GET

Helps to request a specific representation of the resource.

PUT

Updates a resource with a specific representation.

DELETE

Deletes a specified resource.

POST

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()].

[ServiceContract] 
[AspNetCompatibilityRequirements(RequirementsMode = 
           AspNetCompatibilityRequirementsMode.Allowed)] 
[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.Add(empDetail1); 
        EmployeeDetail empDetail2 = new EmployeeDetail(); 
        empDetail2.EmployeeIdentifier = 1234; 
        empDetail2.EmployeeName = "Test2"; 
        empDetail2.ProjectName = "NE"; 
        employeeDetail.Add(empDetail2); 
        return employeeDetail; 
    } 
} 

public class EmployeeDetail 
{ 
    private string employeeName; 
    private int employeeId; 
    private string projectName; 
    public int EmployeeIdentifier
    { 
        get
        { 
            return employeeId; 
        } 
        set 
        { 
            employeeId = value; 
        }
    } 

    public string EmployeeName 
    { 
        get
        { 
            return employeeName; 
        } 
        set
        { 
            employeeName = value; 
        } 
    } 
    
    public string ProjectName 
    { 
        get 
        { 
            return projectName; 
        } 
        set 
        { 
            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="http://schemas.datacontract.org/2004/07/WcfRestService2" 
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
<EmployeeDetail> 
    <EmployeeIdentifier>123</EmployeeIdentifier> 
    <EmployeeName>Test1</EmployeeName> 
    <ProjectName>NE</ProjectName> 
</EmployeeDetail> 
<EmployeeDetail> 
    <EmployeeIdentifier>1234</EmployeeIdentifier> 
    <EmployeeName>Test2</EmployeeName> 
    <ProjectName>NE</ProjectName> 
</EmployeeDetail> 
</ArrayOfEmployeeDetail> 

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.

Authorization

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.

License

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

Share

About the Author

sowmyanarayanan

United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 3 Pinmemberanupam jaiswal24-Nov-12 8:51 
Questionadvantages compares to standard Web service PinmemberSaurabhSavaliya30-Apr-12 2:14 
QuestionGood introductory article on Restful Service PinmemberRupeshKumar20-Oct-11 5:08 
GeneralMy vote of 5 Pinmembereiiov_gr819-Oct-11 3:23 
QuestionPlease do an article on how to deploy to IIS Pinmemberchispnw30-Jun-11 11:54 
AnswerRe: Please do an article on how to deploy to IIS Pinmemberchispnw30-Jun-11 12:26 
GeneralRequest Body PinmemberLuisR119-Apr-11 8:00 
GeneralI did a RESTful one a while back that may be of interest PinmvpSacha Barber21-Jan-11 3:08 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 21 Jan 2011
Article Copyright 2011 by sowmyanarayanan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid