Edit on GitHub

Create your first WebService

This is a quick walkthrough of getting your first web service up and running whilst having a look at the how some of the different components work.

Step 1: Download and Install ServiceStackVS

First we want to install ServiceStackVS Visual Studio extension. The easiest way to do this is to look for it from within Visual Studio by going to Tools > Extensions and Updates... and searching the Visual Studio Gallery as seen below.

Optionally it can be downloaded and installed from the VS.NET Gallery

VS.NET Gallery Download

ServiceStackVS supports VS.NET 2017, 2015 and 2013.

Step 2: Selecting a template

Once the ServiceStackVS extension is installed, you will have new project templates available when creating a new project. For this example, let’s choose ServiceStack ASP.NET Empty to get started.

Once you’ve created your application from the template, you should have 4 projects in your new solution. If you left the default name, you’ll end up with a solution with the following structure.

Step 3: Run your project

Press F5 and run your project!

How does it work?

Now that your new project is running, let’s have a look at what we have. The template comes with a single web service route which comes from the request DTO (Data Transfer Object) which is located in the WebApplication1.ServiceModel project under Hello.cs file.

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

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

The Route attribute is specifying what path /hello/{Name} where {Name} binds it’s value to the public string property of Name.

Let’s access the route to see what comes back. Go to the following URL in your address bar, where is your server address.

http://{BaseUrl}/hello/world

You will see a snapshot of the Result in a HTML response format. To change the return format to Json, simply add ?format=json to the end of the URL. You’ll learn more about formats, endpoints (URLs, etc) when you continue reading the documentation.

If we go back to the solution and find the WebApplication1.ServiceInterface and open the MyServices.cs file, we can have a look at the code that is responding to the browser, giving us the Result back.

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

If we look at the code above, there are a few things to note. The name of the method Any means the server will run this method for any of the valid HTTP Verbs. Service methods are where you control what returns from your service.

Step 4: Exploring the ServiceStack Solution

The Recommended structure below is built into all ServiceStackVS VS.NET Templates where creating any new ServiceStack project will create a solution with a minimum of 4 projects below ensuring ServiceStack solutions starts off from an optimal logical project layout, laying the foundation for growing into a more maintainable, cohesive and reusable code-base:

Host Project

The Host project contains your AppHost which references and registers all your App’s concrete dependencies in its IOC and is the central location where all App configuration and global behavior is maintained. It also references all Web Assets like Razor Views, JS, CSS, Images, Fonts, etc. that’s needed to be deployed with the App. The AppHost is the top-level project which references all dependencies used by your App whose role is akin to an orchestrator and conduit where it decides what functionality is made available and which concrete implementations are used. By design it references all other (non-test) projects whilst nothing references it and as a goal should be kept free of any App or Business logic.

ServiceInterface Project

The ServiceInterface project is the implementation project where all Business Logic and Services live which typically references every other project except the Host projects. Small and Medium projects can maintain all their implementation here where logic can be grouped under feature folders. Large solutions can split this project into more manageable cohesive and modular projects which we also recommend encapsulates any dependencies they might use.

ServiceModel Project

The ServiceModel Project contains all your Application’s DTOs which is what defines your Services contract, keeping them isolated from any Server implementation is how your Service is able to encapsulate its capabilities and make them available behind a remote facade. There should be only one ServiceModel project per solution which contains all your DTOs and should be implementation, dependency and logic-free as Service Contracts decoupled from implementation, enforces interoperability ensuring that your Services don’t mandate specific client implementations and will ensure this is the only project clients need to be able to call any of your Services by either referencing the ServiceModel.dll directly or downloading the DTOs from a remote ServiceStack instance using Add ServiceStack Reference:

Test Project

The Unit Test project contains all your Unit and Integration tests. It’s also a Host project that typically references all other non-Host projects in the solution and contains a combination of concrete and mock dependencies depending on what’s being tested. See the Testing Docs for more information on testing ServiceStack projects.

ServiceStack Integration

ServiceStack’s clean Web Services design makes it simple and intuitive to be able to call ServiceStack Services from any kind of client from a simple Bootstrap Website using jQuery:

<div>
    <div>
        <input class="form-control" id="Name" type="text" placeholder="Type your name">
        <p id="result"></p>
    </div>
</div>
<script>
    $('#Name').keyup(function () {
        var name = $(this).val();
        if (name) {
            $.getJSON('/hello/' + name)
                .success(function (response) {
                    $('#result').html(response.Result);
                });
        } else {
            $('#result').html('');
        }
    });
</script>

To sophisticated Single Page Apps using TypeScript JsonServiceClient, here’s an example using React:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { client } from '../shared';
import { Hello } from '../dtos';

export default class HelloComponent extends React.Component<any, any> {
    constructor(props, context) {
        super(props, context);
        this.state = { result: '' };
    }

    componentDidMount() {
        this.nameChanged(this.props.name);
    }

    async nameChanged(name:string) {
        if (name) {
            let request = new Hello();
            request.name = name;
            let r = await client.get(request);
            this.setState({ result: r.result });
        } else {
            this.setState({ result: '' });
        }
    }

    render() {
        return (
            <div className="form-group">
                <input className="form-control" type="text" placeholder="Your name"
                    defaultValue={this.props.name}
                    onChange={e => this.nameChanged((e.target as HTMLInputElement).value)} />
                <h3 className="result">{this.state.result}</h3>
            </div>);
    }
}

Compare and contrast with other major JavaScript Frameworks:

ServiceStack Services are also easily consumable from all major Mobile and Desktop platforms including native iPhone and iPad Apps on iOS with Swift, Mobile and Tablet Apps on Android with Java or Kotlin, OSX Desktop Appications as well as targetting the most popular .NET Mobile and Desktop platforms including Xamarin.iOS, Xamarin.Android, Windows Store, WPF, WinForms and Silverlight.

Create a WebService from scratch

If you prefer, you can instead create a ServiceStack Web Service from a blank ASP.NET Web Application another popular option is to Add ServiceStack to an existing ASP.NET MVC Application

Explore more ServiceStack features

The EmailContacts solution is a new guidance available that walks through the recommended setup and physical layout structure of typical medium-sized ServiceStack projects, including complete documentation of how to create the solution from scratch, whilst explaining all the ServiceStack features it makes use of along the way.

Community Resources