Walkthrough creating REST Service in WCF 4.0



Objective

This article provides a step to step explanation of how to create a REST based service and how to consume that in a managed client.

Step 1

Create a new project as WCF Service application type.

image1.gif

Step 2

Delete all the default code from IService.cs and Service.svc.cs

Now open Web.Config file and delete the highlighted code below below in Visual Studio 2010. In other words delete all endpoints for existing service.

<system.serviceModel>
<
services>
<
servicebehaviorConfiguration="RestServicePublishing.Service1Behavior"
name="RestServicePublishing.RestService">
<endpointaddress=""binding="wsHttpBinding"contract="RestServicePublishing.IRestService">
<identity>
<
dnsvalue="localhost" />
</identity>
</
endpoint>
<
endpointaddress="mex"binding="mexHttpBinding"contract="IMetadataExchange" />
</service>
</
services>
<
behaviors>
<
serviceBehaviors>
<
behaviorname="RestServicePublishing.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<
serviceMetadatahttpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
<
serviceDebugincludeExceptionDetailInFaults="false"/>
</behavior>
</
serviceBehaviors>
</
behaviors>
</
system.serviceModel>

If you are using VS2010 then delete the code below from Web.Config

image2.gif

Step 3

Right click on Service.svc and open View markup.

image3.gif

In Markup of RestService.cs, add the following code there

Factory="System.ServiceModel.Activation.WebServiceHostFactory"

So after adding code the markup would look like

Markup of RestService.cs

image4.gif

Step 4

Add following referencesto the WCF Service Application project, if you are using VS2010

Microsoft.Http.dll
Microsoft.Http.Extension.dll
System.ServiceModel.Web.dll

Step 5

Add a new project as of type class library and give it name UtilityClasses.

image5.gif

Add a class Number to this class library.

Number.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespaceUtilityClasses
{
    [Serializable]
publicclassNumberService
    {
publicint Number1 { get; set; }
publicint Number2 { get; set; }
    }
}


Step 6

Define the Service Contract as below,

IService1.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.Text;
usingSystem.ServiceModel.Web;
usingUtilityClasses;

namespace WcfService3
{

    [ServiceContract]
publicinterfaceIService1
    {
        [OperationContract(Name="AddParameter")]
        [WebInvoke(UriTemplate = "/",Method="POST")]
int  Add(NumberService n1);
        [OperationContract(Name = "Add")]
        [WebGet(UriTemplate = "/")]
int Add();
 
    }   
 
}


This code is used to construct URI for REST service.

image6.gif

Method parameter says what type of HTTP request; this URI is going to entertain. In this case it is Http POST.

UriTemplate parameter says, what would be URI for this particular method. In this case it is one back-slash, which means it is the root URI of this service.

So, to invoke this method add (), the URI address would be

http://localhost:3602/RestService.svc/

Where 3602 is port number of web server, where this service is running.

Let, if the above code is modified as

image7.gif

Then it would be invoked as

http://localhost:3602/RestService.svc/ADD/MyAdd

Step 7

Now we need to implement the service

Service1.svc.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.ServiceModel.Web;
usingSystem.Text;
usingUtilityClasses;

namespace WcfService3
{

publicclassService1 : IService1
    {

publicint res = 100;

publicint Add(NumberService n1)
        {

res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2);
return res;
        }
publicint Add()
        {
return res;
        } 
    }
}


Step 8

Test the Service in Browser

  1. Build the Service

  2. Right click on Service1.svc and select view in browser.

    image8.gif

    Output 100 is returned in the browser by the service. It is because, below service method. URI of below GET method is mapped to root of the URI. And this method is returning 100.

    image9.gif


Step 9

Consume the service


Add new console project in solution and give it name as ConsoleTestProject.

image10.gif

Add reference of project UtilityClassesAdd following references to the console project.

Microsoft.Http.dll
Microsoft.Http.Extension.dll
System.ServiceModel.Web.dll

Step 10

Program.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Configuration;
usingMicrosoft.Http;
usingMicrosoft.ServiceModel.Web;
usingMicrosoft.ServiceModel.Web.SpecializedServices;
usingSystem.Runtime.Serialization;
usingUtilityClasses;

namespaceConsoleTestProject
{
classProgram
    {
staticvoid Main(string[] args)
        {

uri = "http://localhost:3602/RestService.svc/";
// Calling without parameter
Console.WriteLine(AddWithoutParameter());
Console.Read();
//Calling with parameter
NumberServiceobj = newNumberService() { Number1 = 7, Number2 = 2 };
Console.WriteLine(AddWithParameter(obj));
Console.Read();    

        }

publicstaticstringAddWithoutParameter()
        {
using (HttpResponseMessage response = newHttpClient().Get(uri))
            {

int res = response.Content.ReadAsDataContract<int>();
returnres.ToString();
            }
        }
publicstaticstringAddWithParameter(NumberServiceobj)
        {
using (HttpResponseMessage  response = new HttpClient().Post(uri,HttpContentExtensions.CreateDataContract(obj)))
            {
 
int res = response.Content.ReadAsDataContract<int>();
returnres.ToString();
 
            }
        }
 
        }
    }
}

There are two static methods

  1. AddWithoutParameter() -> To Invoke HTTP Get on Service URI. {In Green}

  2. AddWithParameter() -> To Invoke HTTP POST on Service URI. {In Yellow}

Output

image11.gif

Up Next
    Ebook Download
    View all
    Learn
    View all