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: Install the x dotnet tool
First we want to install the x dotnet tool:
$ dotnet tool install --global x
The dotnet tools are ServiceStack’s versatile companion giving you quick access to a lot of its high-level features including generating mobile, web & desktop DTOs with Add ServiceStack Reference generating gRPC Clients and proto messages, quickly apply gists to your project enabled by ServiceStack’s effortless no-touch Modular features, it even includes a lisp REPL should you need to explore your remote .NET Core App in real-time.
Step 2: Selecting a template
Importantly, the dotnet tools lets you create .NET Core, .NET Framework and ASP.NET Core on .NET Framework projects. Unless you’re restricted to working with .NET Framework you’ll want to start with a .NET Core project template, for this example we’ll start with the Empty web template:
$ x new web WebApp
Step 3: Run your project
Press Ctrl+F5
to run your project!
Watched builds
An alternative to running your project in your IDE is to run a watched build using the dotnet
tool on the command-line:
$ dotnet watch run
Where it will automatically rebuild & restart your App when it detects any changes to your App’s source files.
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 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 its 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
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 which should only reference the impl/dep-free ServiceStack.Interfaces.dll contract assembly to ensure Service contracts are decoupled from its 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
jQuery
ServiceStack’s clean Web Services design makes it simple and intuitive to be able to call ServiceStack Services from any ajax client, e.g. 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>
Dependency-free JsonServiceClient & Typed DTOs in Web Pages
A dep-free alternative to jQuery that works in all modern browsers is to use the
UMD @servicestack/client built into ServiceStack.dll
along with the transpiled
TypeScript Generated DTOs to enable an optimal typed modern async API:
<h2><a href="/json/metadata?op=Hello">Hello</a> API</h2>
<input type="text" id="txtName" onkeyup="callHello(this.value)">
<div id="result"></div>
<script>
var exports = { __esModule:true }, module = { exports:exports }
function require(name) { return exports[name] || window[name] }
</script>
<script src="/js/servicestack-client.js"></script>
<script src="/dtos.js"></script>
<script>
Object.assign(window, exports) //import
var client = new JsonServiceClient()
function callHello(val) {
client.get(new Hello({ name: val }))
.then(function(r) {
document.getElementById('result').innerHTML = r.result;
})
}
</script>
Where you can update your App’s server DTOs by transpiling them to JavaScript & moving to /wwwroot
:
$ npm run dtos
Rich intelli-sense support
Even pure HTML/JS Apps that don’t use TypeScript or any external dependencies will still benefit from the Server
generated dtos.ts
and servicestack-client.d.ts
definitions as Smart IDEs like
Rider can make use of them to provide a rich productive development UX
on both the built-in /js/servicestack-client.js
library:
As well as your App’s server generated DTOs:
Including their typed partial constructors:
So even simple Apps without complex bundling solutions or external dependencies can still benefit from a rich typed authoring experience without any additional build time or tooling complexity.
Using mix to quickly create empty .NET Core Apps
As this requires no external deps or prescribed JS frameworks, it’s used in the init and init-lts mix scripts which you can quickly add & run using the x dotnet tool:
$ dotnet tool install --global x
Which can be used to quickly create & run a new .NET Core App in an empty directory:
$ md ProjectName && cd ProjectName
$ x mix init
$ dotnet run
Which will install the init Gist to your local directory using the ProjectName
directory name for the new Project name.
Empty VB.NET .NET Core App
Use init-vb
to create a VB .NET Core App:
$ md ProjectName && cd ProjectName
$ x mix init-vb
$ dotnet run
Which will install the init-vb Gist.
Empty F# .NET Core App
Use init-fsharp
to create a F# .NET Core App:
$ md ProjectName && cd ProjectName
$ x mix init-vb
$ dotnet run
Which will install the init-fsharp Gist.
TypeScript or JavaScript SPA Apps
The same TypeScript JsonServiceClient is also used in more sophisticated JavaScript Apps like React Native to node.js Server Apps as well as all TypeScript SPA Project Templates, such as this example using React:
import './hello.css';
import * as React from 'react';
import { Input } from '@servicestack/react';
import { client } from '../../shared';
import { Hello } from '../../shared/dtos';
export interface HelloApiProps {
name: string;
}
export const HelloApi: React.FC<any> = (props:HelloApiProps) => {
const [name, setName] = React.useState(props.name);
const [result, setResult] = React.useState('');
React.useEffect(() => {
(async () => {
setResult(!name ? '' : (await client.get(new Hello({ name }) )).result)
})();
}, [name]); // fires when name changes
return (<div>
<div className="form-group">
<Input value={name} onChange={setName} placeholder="Your name" />
<h3 className="result pt-2">{ result }</h3>
</div>
</div>);
}
Compare and contrast with other major SPA JavaScript Frameworks:
- Vue.js HelloApi.vue
- React HelloApi.tsx
- Angular HelloApi.ts
- Svelte Home.svelte
- Aurelia hello.ts
- Angular v4 hello.ts
- Angular.js v1.5 using $http
Full .NET Project Templates
The above init
projects allow you to create a minimal web app, to create a more complete ServiceStack App with the recommended project structure, start with one of our C# project templates instead:
C# Project Templates
Integrated in Major IDEs and popular Mobile & Desktop platforms
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 Applications as well as targeting the most popular .NET Mobile and Desktop platforms including Xamarin.iOS, Xamarin.Android, Windows Store, WPF and WinForms.
Explore ServiceStack
When you’re ready to dive in further checkout our Explore ServiceStack Guide.
Community Resources
- Creating A Simple Service Using ServiceStack by Shashi Jeevan
- Introducing ServiceStack by @dotnetcurry
- Create web services in .NET in a snap with ServiceStack by @techrepublic
- How to build web services in MS.Net using ServiceStack by @kishoreborra
- Creating a Web API using ServiceStack by Lydon Bergin
- Getting Started with ServiceStack: Part 1 by Lydon Bergin
- Getting started with ServiceStack – Creating a service
- ServiceStack Quick Start by @aarondandy
- Fantastic Step-by-step walk-thru into ServiceStack with Screenshots! by @nilsnagele
- Your first REST service with ServiceStack by @cyberzeddk
- New course: Using ServiceStack to Build APIs by @pluralsight
- ServiceStack the way I like it by @tonydenyer
- Generating a RESTful Api and UI from a database with LLBLGen by @mattjcowan
- ServiceStack: Reusing DTOs by @korneliuk
- Using ServiceStack with CodeFluent Entities by @SoftFluent
- ServiceStack, Rest Service and EasyHttp by @chrissie1
- Building a Web API in SharePoint 2010 with ServiceStack
- REST Raiding. ServiceStack by Daniel Gonzalez
- JQueryMobile and ServiceStack: EventsManager tutorial / Part 3 by +Kyle Hodgson
- Like WCF: Only cleaner! by +Kyle Hodgson
- ServiceStack I heart you. My conversion from WCF to SS by @philliphaydon
- ServiceStack vs WCF Data Services
- Creating a basic catalogue endpoint with ServiceStack by 7digital
- Buildiing a Tridion WebService with jQuery and ServiceStack by @robrtc
- Anonymous type + Dynamic + ServiceStack == Consuming cloud has never been easier by @ienablemuch
- Handful of examples of using ServiceStack based on the ServiceStack.Hello Tutorial by @82unpluggd