Software Development

Create web services in .NET in a snap with ServiceStack

You can build a functioning web service in .NET in no time by using the ServiceStack framework. Here's how.

webdevelopment_1600x1200_021014.jpg
 Image: arhon

I recently stumbled upon ServiceStack while working with NancyFX. ServiceStack provides a simple framework for creating and rolling out .NET-based web services and applications.

Here's a quick tour of ServiceStack (which has been around since 2008) to get a feel for what it offers, with an emphasis on building web services.

Keep it simple

With so many technologies and products available, simplicity is one of the most attractive features. I am not saying I have a hard time keeping up, but there is only so much time, thus I am more likely to use something with a smaller learning curve.

With that said, I am no fan of Windows Communication Foundation (WCF) (my first venture into WCF was painful). WCF, like other .NET frameworks, is heavy and often overly complex while requiring lots of reading and tinkering to gain a footing. While my WCF-based solution eventually worked, I scratched my head at the complexity of it. The Web API is somewhat better, but I went from a standing start to a functioning web service using ServiceStack in no time. It was a simple example, but try that with something like WCF and watch the time melt away.

ServiceStack has many great features as outlined on its architecture overview. The items that make it attractive to me are as follows:

  • Model driven, code-first approach to building applications. This lets the developer code as opposed to tedious tasks like editing configuration files; however, a line in the web.config is necessary. It is built on top of basic ASP.NET with no new concepts or constructs that can be a hindrance down the road.
  • There are no arcane configuration settings to worry about (yes, I am talking about you WCF).
  • It supports both Mono and standard .NET, so run it on Windows or Linux. They say their site runs on Linux, but I did not verify the claim.
  • JSON, XML, and SOAP support is standard.
  • Strong-typed Data Transfer Objects (DTOs) are created as objects, thus not tied to HTTP or anything else. This simplifies testing as well as theoretically makes the objects reusable. The documentation says ServiceStack was influenced by Martin Fowler's Data Transfer Object Pattern.
  • Exception handling is automatic. This is nothing earth shattering, but it is nice to have by default. It supports basic C# exceptions that are injected into the ResponseStatus property of the Response object.

Watch it go

I will build a basic web service; this is accomplished with a standard ASP.NET site, so create an empty ASP.NET project in Visual Studio. ServiceStack uses three objects (or DTOs): request, response, and the actual service. The request and the response are standard objects, while the service inherits from the ServiceStack.Service class.

ServiceStack is available via NuGet and can be installed from the Package Manager Console in Visual Studio (Install-Package ServiceRequest) (Figure A). The base package is ServiceRequest with additional packages available for extra features like using it with RavenDB or Mongo along with Razor for MVC interfaces and many more that can be viewed with the NuGet Package Manager (Figure B).

Note: ServiceStack is free for development and testing, but you will need to purchase it for actual production usage.

Figure A

servicestackfiga080514.jpg

Installing ServiceStack via the Visual Studio Package Manager Console.

Figure B

servicestackfigb080514.jpg

Searching for ServiceStack packages in Visual Studio NuGet Package Manager.

Once it is installed, the following block needs to be added to the site's web.config file.

<system.webServer>
 <validation validateIntegratedModeConfiguration="false" />
<handlers>
<add path="*" 
name="ServiceStack.Factory" 
preCondition="integratedMode"
type="ServiceStack.HttpHandlerFactory, ServiceStack"
 verb="*" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>

The next steps are creating our objects -- this includes request and response objects as well as a class for the web service. I begin with the request object, which is a standard C# class with the special Route attributes to define what routes it supports. It has one property called Address. Notice it uses the ServiceStack library to utilize the routes.

using System;
using ServiceStack;
namespace ServiceStackDemo {
public class TechRepublicRequest  {
public string Address { get; set; }  }  }

The Response object has one property string property called Result. This will be used by the web service to formulate what is returned when it is called.

using System;
using ServiceStack;
namespace ServiceStackDemo {
public class TechRepublicResponse   {
public string Result { get; set; }  }  }

While the request and response objects are standard classes, the service class inherits from the ServiceStack.Service class. It returns a new instance of our response class with the Result property populated for any request sent to the service.

using System;
using ServiceStack;
namespace ServiceStackDemo {
[Route("/tr")]
[Route("/tr/{Address}")]
public class TechRepublicService : Service   {
public object Any(TechRepublicRequest)   {
return new TechRepublicResponse { Result = "Hey - " + request.Address };
}  }  }

The final piece of the puzzle is telling the system where to find the web service. This is achieved in a Global.asax file (which will need to be added to an empty ASP.NET project). A singleton AppHost class is added in Global.asax along with initializing it in the Application_Start event.

public class TechRepublicAppHost : AppHostBase    {
public TechRepublicAppHost() : base("Web Service Test", typeof(TechRepublicService).Assembly) { }
public override void Configure(Funq.Container container)  {
}  }
protected void Application_Start(object sender, EventArgs e)   {
new TechRepublicAppHost().Init();
}

You can register service dependencies, define routes, and much more within the empty Configure method listed above. With this simple service created (and deployed to Azure), Figure C shows the metadata loaded (using metadata in path as shown in address bar). Figure D shows the JSON options for the TechRepublicRequest service listed in Figure C.

Figure C

servicestackfigc080514.jpg

Viewing service metadata once code is compiled and deployed.

Figure D

servicestackfigd080514.jpg

Viewing the JSON options for the service (clicking the JSON link in Figure C).

This is a simple example that just scratches the surface of what is available; the online documentation provides plenty of information.

It is nice to have options

I am not a big fan of Microsoft's .NET offerings for building web services, so options like ServiceStack and NancyFX are appealing. The simplicity of their approach and the strong performance makes them great choices for a project.

I understand when developers shy away from alternatives, either fearing support will eventually dry up or not wanting to be burdened with using something new. However, it is great to have options and competition pushes Microsoft to continue to enhance and innovate, as evidenced by the company's presence at the recent OSCON open source convention.

Also read

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

2 comments
vstaduri
vstaduri

Hi... I like this wallpaper. I found few more high resolution wallpapers here:
http://www.hdwallpaperspx.com/travel-and-world/bellagio-las-vegas-hd-wallpaper

HD Wallpapers,HD Desktop Wallpapers,HD Images,HD Pictures,HD Photos,3D,Interior Design,Celebriries,Bikes,Cars,Landscape,Planes,Icecream,Love,Lakes,Nature,Inspirational,

Quotes,Islands,Festivals,Paintings,Anime,Food,Babies,Music,Photography,Travel and World,Brands,Logos

Editor's Picks