Tuesday, January 13, 2009

Making a REST service with VB and WCF

REST which stands for Representational State Transfer is a way of sending data over the Internet without an additional message layer.  Standard web services use soap for there message header.  In this example we will create a service that uses the northwind database to send a  list of the products for a category.

Lets start by create a new VB web application. In that web application add a Ado.Net Entities data model.  In that class add the northwind database's product class.

Now add a service named Service1 to the web application.  Lets start by modify the web.config for the service to support rest.  First remove the ServiceBehavior section and add a endpointBehaviors section for webHttp.  In the endpoint we have to change the binding to webHttpBinding and the behaviorConfiguration to the webBehavior we created.

    <behavior name="webBehavior">
    <serviceHostingEnvironment aspNetCompatibilityEnabled="True"></serviceHostingEnvironment>
        <service name="RestTest.Service1">
            <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" bindingConfiguration="" contract="RestTest.IService1">

When we added the service we got 2 items the wcf service and an interface for the service.  Before we go any further we need to add a reference to system.servicebehavior.web  

In the Interface we need to define the how the categoryId is passed to the service.  In this example it expects product/categoryID in the url for the service

Imports System.ServiceModel
Imports System.ServiceModel.Web
<ServiceContract()> _
Public Interface IService1
    <OperationContract()> _
    <WebGet(UriTemplate:="Product/{categoryID}", ResponseFormat:=WebMessageFormat.Xml, BodyStyle:=WebMessageBodyStyle.Bare)> _
    Function GetProducts(ByVal categoryId As String) As List(Of Products)
End Interface

In the service we need to set the AspNetCompatibilityMode and write some code to return the products

Imports System.ServiceModel.Activation
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1
    Implements IService1
    Public Function GetProducts(ByVal categoryId As String) As System.Collections.Generic.List(Of Products) Implements IService1.GetProducts
        Dim dc As New NorthwindEntities
        Dim q = From p In dc.Products Select p Where p.CategoryID = CInt(categoryId)
        Return q.ToList
    End Function
End Class

To call the service you would use a url like http://localhost:2050/Service1.svc/Product/7

you will get an xml file like this returned