ServiceStack Home

Creating a Web service from scratch with Service Stack

This tutorial will go through and develop and call a simple Hello world Web Service from scratch using Service Stack and VS.NET.

Installing via NuGet

If you have NuGet you can skip steps 1 - 3 below by installing one of the NuGet Host packages below:

Install ServiceStack Only at root path /

Create an empty ASP.NET Web Application and

PM> Install-Package ServiceStack.Host.AspNet

Install ServiceStack Side-by-Side with ASP.NET MVC at custom path /api

Create an empty ASP.NET MVC Web Application and

PM> Install-Package ServiceStack.Host.Mvc

Completing the NuGet Installation

The NuGet package provides an AppHost template in your project at App_Start\AppHost.cs and some App_Start\WebServiceExamples.cs to get you started.

After looking at the README.txt - Skip the Manual Installation instructions below and start exploring ServiceStack features at:

Viewing your Web Service >>

Install Manually - 1. Creating your application

Create a new ASP.NET Web Application by going into Visual Studio and selecting File -> New -> Project on the File menu.

New ASP.NET Project

2. Configuring Service Stack to run in your application

Add a reference to the ServiceStack dlls with:

PM> Install-Package ServiceStack

There are 2 supported options available to register ServiceStack in your ASP.NET application Web.config:

a) You do not require an existing Web Framework - Host from the root path: /

You can host at the root path / when you don't need to use an existing Web Framework with your ServiceStack web services (i.e. project only has static files)

The configuration below allows you to host your webservices from the root path: /

    <system.web>       <httpHandlers>         <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*"/>       </httpHandlers>     </system.web>     <!-- Required for IIS7 -->     <system.webServer>       <modules runAllManagedModulesForAllRequests="true"/>       <validation validateIntegratedModeConfiguration="false" />       <handlers>         <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />       </handlers>     </system.webServer>

b) You want to use ServiceStack with an existing Web Framework - Host web services at: /custompath

In order to avoid conflicts with your existing ASP.NET web framework it is recommended to host your ServiceStack web services at a custom path.
This will allow you to use ServiceStack together with an existing web framework e.g. ASP.NET MVC 3 or FUBU MVC, etc.

The location configuration below hosts your webservices at custom path: /api

  <!-- ServiceStack: Required to host at: /servicestack -->   <location path="api">     <system.web>       <httpHandlers>         <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*"/>       </httpHandlers>     </system.web>     <!-- Required for IIS7 -->     <system.webServer>       <modules runAllManagedModulesForAllRequests="true"/>       <validation validateIntegratedModeConfiguration="false" />       <handlers>         <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />       </handlers>     </system.webServer>   </location>   <!-- Required for MONO -->   <system.web>     <httpHandlers>       <add path="api*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*"/>     </httpHandlers>   </system.web>   <!-- Required for IIS7 -->   <system.webServer>     <!-- ServiceStack: Required -->     <validation validateIntegratedModeConfiguration="false"/>   </system.webServer>

Note: Due to limitations in IIS 6 - the /custompath must end with .ashx, e.g: path="api.ashx"

To avoid conflicts with ASP.NET MVC add ignore rule in Global.asax RegisterRoutes method e.g: routes.IgnoreRoute ("api/{*pathInfo}");

3. Creating your first Web Service

For simplicity we will add the Web Service and the start up script all in the same Global.asax.cs. To do this Right-click on your project and go
Add -> New Item then select the Global Application class.

Within the same file add the following code:

1. Create the name of your Web Service (i.e. the Request DTO)

    /// <summary>     /// Define your ServiceStack web service request (i.e. the Request DTO).     /// </summary>         public class Hello     {         public string Name { getset; }     }

2. Define what your Web Service will return (i.e. Response DTO)

    /// <summary>     /// Define your ServiceStack web service response (i.e. Response DTO).     /// </summary>     public class HelloResponse     {         public string Result { getset; }     }

3. Create your Web Service implementation

    /// <summary>     /// Create your ServiceStack web service implementation.     /// </summary>     public class HelloService : IService     {         public object Any(Hello request)         {             //Looks strange when the name is null so we replace with a generic name.             var name = request.Name ?? "John Doe";             return new HelloResponse { Result = "Hello, " + name };         }     }

Registering your web services and starting your application

The final step is to Configure setup to tell Service Stack where to find your web services:

Web Service AppHost Singleton

    public class Global : System.Web.HttpApplication     {         /// <summary>         /// Create your ServiceStack web service application with a singleton AppHost.         /// </summary>                 public class HelloAppHost : AppHostBase         {             /// <summary>             /// Initializes a new instance of your ServiceStack application, with the specified name and assembly containing the services.             /// </summary>             public HelloAppHost() : base("Hello Web Services"typeof(HelloService).Assembly) { }             /// <summary>             /// Configure the container with the necessary routes for your ServiceStack application.             /// </summary>             /// <param name="container">The built-in IoC used with ServiceStack.</param>             public override void Configure(Container container)             {                 //Register user-defined REST-ful urls. You can access the service at the url similar to the following.                 //http://localhost/ServiceStack.Hello/servicestack/hello or http://localhost/ServiceStack.Hello/servicestack/hello/John%20Doe                 //You can change /servicestack/ to a custom path in the web.config.                 Routes                   .Add<Hello>("/hello")                   .Add<Hello>("/hello/{Name}");             }         }         protected void Application_Start(object sender, EventArgs e)         {             //Initialize your application             (new HelloAppHost()).Init();         }     }

Done! You now have a working application :)

Viewing your Web Services

Now that you have a working Web Service lets see what ServiceStack does for you out of the box:

The Web Service Index Metadata page

If everything is configured correctly you can go to the /metadata to see a list of your web services and the various end points its available on.

Service Stack Metadata page

The Metadata page contains:

The different ways of calling your Web Service

Without any configuration required, your web services are callable via the following endpoints, formats and calling conventions.

XML (POX), JSON, JSV, CSV urls

/[xml|json|html|jsv|csv]/[reply|oneway]/[servicename]

SOAP Web Service urls

/[soap11|soap12]

User defined REST-ful urls

Accessible via any REST-ful urls defined using the [RestService] Attribute. e.g. in this case:

/hello/{Name}

XML, JSON, HTML5, JSV, CSV Web Services via HTTP GET or POST

CONTENT TYPE HTTP GET HTTP POST CONTENT TYPE HTTP POST FORM DATA
XML /xml/reply/Hello?Name=World /xml/reply/Hello
JSON /json/reply/Hello?Name=World /json/reply/Hello
HTML /html/reply/Hello?Name=World /html/reply/Hello
JSV /jsv/reply/Hello?Name=World /jsv/reply/Hello
CSV /csv/reply/Hello?Name=World /csv/reply/Hello

CONTENT TYPE

The endpoint type and resulting serialization format of your web service.

HTTP GET

The url to call your web service using only the url and the query string to populate the request.

NOTE: Service Stack also lets you submit any arbitary complex type (using JSV format) via the query string or form data

HTTP POST CONTENT TYPE

You can HTTP POST the 'Content Type' representation of the Request DTO to the same url. Check the links to the metadata page for examples of this.

HTTP POST FORM DATA

As an alternative to posting the Content Type, each service also accepts x-www-form-urlencoded Content-Types allowing you to call each web service using a HTML FORM. Here is the HTML for the live examples:

<form action="api/xml/reply/Hello" method="post">    <label>Name:</label>    <input type="text" name="Name" value="World!" />    <input type="submit" /> </form>

Example:

SOAP Web Services

SOAP VERSION WSDL + END POINTS SOAP EXAMPLE
SOAP 1.1 /soap11 soap11/metadata?op=Hello
SOAP 1.2 /soap12 soap12/metadata?op=Hello

WSDL + END POINTS

A HTTP GET on the url returns the WSDL, while HTTP POST-ing a SOAP Request calls the web service.

SOAP EXAMPLE

Shows example of what a SOAP Request looks like.

REST Web Services

A new addition to Service Stack is the ability to define your own custom urls letting you expose your web services via REST-ful urls.

Defining user-defined REST-ful urls can be done in one of two ways:

e.g: the following mapping:

[Route("/hello/{Name}")]

Allows this web service to be called with: /hello/World!

Just like the other endpoints, REST-ful urls can also be called with a HTML FORM POST. However in this case we need to define another mapping so it matches the url that we want, i.e.

[Route("/hello")]

Which lets us now call this web service using the following HTML:

<form action="api/hello?format=json" method="post">    <label>Name:</label>    <input type="text" name="Name" value="World!" />    <input type="submit" /> </form>

Example:

This makes it very easy to Ajax-ify your existing HTML forms, cleanly, without messy configuration and generated code mandated by other options.

Calling Web Services from Code

Using DTOs to define your web service interface makes it possible to provide strong-typed generic service clients without any code-gen or extra build-steps, leading to a productive end-to-end type-safe communication gateway from client to server.

All REST and ServiceClients share the same interfaces so they can easily be replaced (for increased perf/debuggability/etc) with a single line of code as seen in the Hello Service Integration tests.

C#/.NET Clients can call the above Hello Service using any of the JSON, JSV, XML or SOAP Service Clients as well as a Silverlight, JavaScript, Dart or even MQ Client.

Where to now?

Northwind Database Examples

Now that you've got the hang of how easy it is to create a simple web service, check out the Northwind Database examples to see how useful servicestack becomes with just a little db code.