Creating A Simple Service Using ServiceStack

Introduction

ServiceStack is a framework similar to ASP.NET MVC, Web API, WCF etc. used to build web applications and services. The framework is platform independent and the applications built using it can be run on both Windows and Linux. In this article we will build a simple REST based web service that will return ‘Note’ details associated with a given ‘Id’. When the ‘Id’ parameter is not specified in the request all the ‘Notes’ are returned to the client.

Pre-requisites

Following are the pre-requisites:

  1. Visual Studio 2015.
  2. ‘ServiceStack’ NuGet Package.

Here are the steps to create the base project:

  1. Create a new project using the ‘Empty’ ASP.Net application project template.
  2. Add ‘Global.asax’ file to the project.
  3. Install the ‘ServiceStack’ NuGet package in this project.

Request and Response

The ServiceStack framework uses the Data Transfer Objects design pattern. This requires defining different classes for the Request and Response messages for a given Service that are independent of the domain specific classes that are used inside the Service. We will create two classes for this.

    Add request and response DTO classes

    Add the following two classes that represent the input and output DTO objects of the NotesService.
    1. [Route("/notes")]  
    2.   [Route("/notes/{Id}")]  
    3.   class NoteRequestDTO  
    4.   {  
    5.       public int? Id { getset; }  
    6.   }  
    7.   
    8.   class NoteResponseDTO  
    9.   {  
    10.       public string Note { getset; }  
    11.   }  
    Define a Route mapping for the Request DTO

    The NoteRequestDTO class is used to define the URL Route used to invoke the service. Here we have defined two routes.

    • [Route("/notes")]: This defines the URL for retrieving all the Notes.
    • [Route("/notes/{Id}")]: This defines the URL for retrieving a specific Note.

    NotesService

    The NotesService class defines the implementation of a service that returns Notes. This class should extend the ‘Service’ class of ServiceStack. The class defines only one method ‘Any’ which will Handle all the HTTP method types, viz., GET, POST, PUT and DELETE. This method takes the Request DTO class defined earlier as a parameter. The return type varies based on the input. The service has a predefined list of Notes. ServiceStack framework will parse the input and fills the Request DTO object. When the Id parameter is not passed we need to return the whole Notes collection. If the specific Id is passed, we look up and return the corresponding Note. If there is no Note found corresponding to the Id then we just return an empty string.

    1. namespace NotesServer  
    2. {  
    3.     class NotesService : Service  
    4.     {  
    5.         //Collection of Notes  
    6.         private Dictionary<intstring> notes = new Dictionary<intstring>() {  
    7.                                                         { 1, "Hello" },  
    8.                                                         { 2, "World" } };  
    9.   
    10.         public object Any(NoteRequestDTO request)  
    11.         {  
    12.             //Check if the Note Id was passed in the Request.  
    13.             if (!request.Id.HasValue)  
    14.             {  
    15.                 //Note Id is not present in the Request, hence return all Notes.  
    16.                 var notesResponse = from note in notes  
    17.                                         select new NoteResponseDTO {  
    18.                                             Note = note.Value  
    19.                                         };  
    20.   
    21.                 return notesResponse.ToList();  
    22.             }  
    23.   
    24.             //Note Id is present in the Request. Check if there is a corresponding Note.  
    25.             if (notes.ContainsKey(request.Id.Value))  
    26.             {  
    27.                 //Return the corresponding Note.  
    28.                 return new NoteResponseDTO { Note = notes[request.Id.Value] };  
    29.             }  
    30.             else  
    31.             {  
    32.                 //Return Empty string as there is no corresponding Note.  
    33.                 return string.Empty;  
    34.             }  
    35.         }  
    36.     }  
    37. }  

     

NotesAppHost

The service now needs to be bootstrapped. This is done by creating a class that is derived from AppHostBase. The base class constructor needs to be initialized with the Service type that it is bootstrapping. Then the abstract method Configure needs to be implemented.
  1. namespace NotesServer.AppHost  
  2. {  
  3.     public class NotesAppHost : AppHostBase  
  4.     {  
  5.         public NotesAppHost() : base("Notes Service"typeof(NotesService).Assembly)  
  6.         {  
  7.   
  8.         }  
  9.   
  10.         public override void Configure(Container container)  
  11.         {  
  12.   
  13.         }  
  14.     }  
  15. }  
Start Listening

The web service needs to be initialized so that it can accept the requests. Inside the ASP.Net Web site this should done inside the Global.asax file. Add the ‘Global.asax’ if not already present.

Add the Host Initialization

Added the following in Application_Start() method of Global.asax file.
  1. protected void Application_Start(object sender, EventArgs e)  
  2. {  
  3.    new NotesAppHost().Init();  
  4. }  
Register the ServiceStack with ASP.Net framework

Add the following configuration element to web.config at the same level as <system.web>
  1. <system.webServer>  
  2.   <validation validateIntegratedModeConfiguration="false" />  
  3.   <handlers>  
  4.     <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack"   
  5.          verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />  
  6.   </handlers>  
  7. </system.webServer>  
Running the Web Service

Build and run from the Visual studio. The website metadata page will open showing various ways of invoking the service. The following image shows the browser screenshot.

service

Invoking the Web Service

We can invoke the service using the browser as in the following screenshot:
  1. Get all Notes.

    Get all Notes

  2. Get a specific Note.

    Get a specific Note

Conclusion

This article explains the procedure to build and test a simple service using the ServiceStack framework.


Similar Articles