Implementing a client and services with ServiceStack

ServiceStack, is a lightweight framework for writing web services.

Getting Started

Let’s just create a “default” service and client first.

See Create your first WebService for information on creating your first service. I’ll replicate some of the steps here also…

  • Using Visual Studio, Tools | Extensions and Updated, search for ServiceStack templates and install (if not already installed)
  • Create a new ServiceStack ASP.NET Empty project (target .NET 4.6)
  • Build and run

By default this will create a service which accepts a Hello object and returns a HelloResponse (for reference, here’s those classes)

public class HelloResponse
{
   public string Result { get; set; }
}

[Route("/hello/{Name}")]
public class Hello : IReturn<HelloResponse>
{
   public string Name { get; set; }
}

Note: The Hello class “implements” IReturn (which actually is just a marker interface, i.e. no methods) to give our client the ability to pass Hello objects (and hence have type safety etc.) to the service and inform the client what response to expect.

We can test the service using our web browser, for example my server is running on the localhost on port 50251, so typing the URL http://localhost:50251/Hello/Bob (note: the Route attribute defines the “route” to the specific method etc. hence you can see how this maps to the URL we used) will result in the Hello class being run with the argument Bob as the Name. The response will be displayed in the browser, along the lines of Result Hello, Bob!. This is the same result we’ll be expecting from our client app.

But how did we get the result “Hello, World!” from the server? This is where the MyService implementation in the generated server code comes in. When the server’s AppHost starts up it looks for services. These are then used to intercept/generate calls and responses. See the code below (copied from the generated code)

public class MyServices : Service
{
   public object Any(Hello request)
   {
      return new HelloResponse 
      { 
         Result = "Hello, {0}!".Fmt(request.Name) 
      };
   }
}

Let’s create a client app.

  • Create a Console application
  • From the Package Manager Console, run Install-Package ServiceStack.Client
  • Copy the Hello and HelloResponse classes from the service to the client
  • In the Main method add the following
    var client = new JsonServiceClient("http://localhost:50251/");
    var resp = client.GetAsync(new Hello { Name = "Bob" })
       .Success(tsk =>
       {
          Console.WriteLine(tsk.Result);
       })
       .Error(e =>
       {
          Console.WriteLine(e.Message);
       });
    
    Console.ReadLine();
    

For the client Api we could have called the service using

var resp = client.GetAsync<HelloResponse>("/hello/World");

if preferred, and this will do away for the need for the Hello class in the client.