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:
- Visual Studio 2015.
- ‘ServiceStack’ NuGet Package.
Here are the steps to create the base project:
- Create a new project using the ‘Empty’ ASP.Net application project template.
- Add ‘Global.asax’ file to the project.
- 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.
- [Route("/notes")]
- [Route("/notes/{Id}")]
- class NoteRequestDTO
- {
- public int? Id { get; set; }
- }
-
- class NoteResponseDTO
- {
- public string Note { get; set; }
- }
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.
- namespace NotesServer
- {
- class NotesService : Service
- {
-
- private Dictionary<int, string> notes = new Dictionary<int, string>() {
- { 1, "Hello" },
- { 2, "World" } };
-
- public object Any(NoteRequestDTO request)
- {
-
- if (!request.Id.HasValue)
- {
-
- var notesResponse = from note in notes
- select new NoteResponseDTO {
- Note = note.Value
- };
-
- return notesResponse.ToList();
- }
-
-
- if (notes.ContainsKey(request.Id.Value))
- {
-
- return new NoteResponseDTO { Note = notes[request.Id.Value] };
- }
- else
- {
-
- return string.Empty;
- }
- }
- }
- }
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.
- namespace NotesServer.AppHost
- {
- public class NotesAppHost : AppHostBase
- {
- public NotesAppHost() : base("Notes Service", typeof(NotesService).Assembly)
- {
-
- }
-
- public override void Configure(Container container)
- {
-
- }
- }
- }
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.
- protected void Application_Start(object sender, EventArgs e)
- {
- new NotesAppHost().Init();
- }
Register the ServiceStack with ASP.Net framework
Add the following configuration element to web.config at the same level as <system.web>
- <system.webServer>
- <validation validateIntegratedModeConfiguration="false" />
- <handlers>
- <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack"
- verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
- </handlers>
- </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.
Invoking the Web Service
We can invoke the service using the browser as in the following screenshot:
- Get all Notes.
- Get a specific Note.
Conclusion
This article explains the procedure to build and test a simple service using the ServiceStack framework.