# Why ServiceStack Source: https://docs.servicestack.net/why-servicestack
ServiceStack is a batteries-included framework for building **typed, message-based APIs** in .NET. Most frameworks give you a way to return JSON from a method. ServiceStack starts one level up: you describe *what the message is*, and everything downstream - the routes, the docs, the validation, the admin UIs, the native clients, the AI tool definitions - is generated from that single description. The result is a framework where **adding a capability usually means adding an attribute**, not adding a project. ## One contract, everything else generated Here is a complete, working, queryable, secured API: ```csharp [ValidateIsAuthenticated] [Description("Find bookings matching the specified criteria")] public class QueryBookings : QueryDb { public int[] Ids { get; set; } } ``` That single Request DTO gives you a REST API with filtering, paging and sorting, an executable API Explorer UI, a portable JSON Schema, an entry in your OpenAPI spec, a Locode CRUD App, an AI-callable tool and native typed clients in **15 languages** - with no Service implementation, no controller, no DTO mapping and no SDK project.
## Write the contract. Skip the rest. The clearest way to see the value is to compare what you write against what you'd otherwise have to write - and keep writing, for every platform, forever.
## Rich UIs your APIs get for free Every ServiceStack App ships with capable, authorized management UIs that are **generated from your APIs at runtime**. There is nothing to install, no separate admin project to maintain, and no drift between your API and the tools used to operate it.
::: info All Admin UIs respect your App's existing authentication and authorization - users only see the screens and actions their roles allow. ::: ## Typed clients in 15 languages [Add ServiceStack Reference](/add-servicestack-reference) reads the metadata your App already publishes and generates a **single native source file** of DTOs for the target language, paired with an idiomatic Service Client that understands the contract: response types, routes, HTTP methods, authentication, structured errors, validation failures and AutoQuery conventions.
.NET
C# · F# · VB.NET
Web & Scripting
TypeScript · JavaScript · Python · PHP · Ruby
Mobile
Swift · Java · Kotlin · Dart
Cloud & Systems
Go · Rust · Zig
Two commands in any language - add the client, then generate the DTOs:
Re-run the same command whenever your API changes. New fields appear in the generated DTOs; removed or renamed members become **compile errors in the consuming App** instead of runtime surprises in production. ::: tip This is the opposite of the SDK treadmill. There's no per-platform SDK repo to version, publish and document - the contract *is* the SDK. ::: ## AI-native, without an AI backend The metadata that generates typed clients also describes your APIs well enough for a model to use them. So instead of building a parallel "AI API" with its own auth, its own schemas and its own risk profile, ServiceStack lets AI call the APIs you already have - **as the signed-in user, through the same pipeline as every other client**.
Because approval forms are generated from the same schema that powers API Explorer, users can **inspect and correct** what a model is about to submit before anything is written. And since it's your normal request pipeline, your authorization, validation, filters and business logic all still apply - a model cannot do anything the current user couldn't do themselves.
AI Chat

A complete multi-provider AI App at /chat using your App's existing users, database and security boundary.

MCP Server

Expose the same approved APIs to external AI Assistants over the Model Context Protocol.

PDF Studio

Design documents with AI, publish immutable revisions, then render production PDFs with no LLM at runtime.

## Host it your way ServiceStack Services are decoupled from HTTP, from any UI technology and from any single host. The same implementation can serve a website, a mobile App, a queue consumer and a gRPC endpoint.
## Why message-based APIs ServiceStack's design follows [Martin Fowler's Data Transfer Object pattern](https://martinfowler.com/eaaCatalog/dataTransferObject.html): when a call crosses a process boundary, send *one well-defined message* rather than many fine-grained calls. This isn't stylistic. A remote call is the most expensive thing in general-purpose computing, and an interface that hides that cost behind method signatures encourages exactly the wrong shape of system.
RPC-style
  • A new method for every way a client wants to ask
  • Adding a parameter is a breaking change
  • N chatty round-trips where one would do
  • Can't be cached, queued, batched or deferred
  • Client-shaped APIs that outlive the client
Message-based
  • One coarse-grained message serves many use cases
  • Adding a field is additive and backwards-compatible
  • Any combination fulfilled in a single call
  • Cacheable, queueable, batchable, proxyable
  • Service-shaped APIs that outlive their consumers
Because the message is a plain POCO with no framework artifacts in it, the *same type* is your server contract, your client contract, your validation schema, your documentation, your UI definition and your AI tool definition. That's the entire trick - and it's why enabling a new capability so often costs one attribute instead of one project. Read the long-form argument in [Advantages of message-based Web Services](/advantages-of-message-based-web-services) and [Why remote services use DTOs](/why-remote-services-use-dtos). ## Everything in the box
## What this means in practice
Less code to maintain

Admin screens, SDKs, docs and API clients are generated from the contract instead of hand-written and left to drift.

Fewer moving parts

Auth, jobs, caching, messaging, logging and analytics ship together and are designed to work together.

Genuinely testable

Services are dependency-free classes and typed clients make integration tests read like unit tests.

Fast by default

Built on high-performance serializers and data access, on the fastest APIs each .NET runtime offers.

Investment preserved

Libraries are continuously improved across 20+ years - not abandoned and replaced.

Commercially supported

Actively developed with paid support, and free for individuals & OSS.

## Start in 60 seconds
🚀
Create a project

Pick a template and download a ready-to-run App - Blazor, Vue, React, MVC, API-only and more.

servicestack.net/start →
📘
Build your first API

A guided walkthrough from empty project to a working, documented, typed API.

Get started →
✨
See what's new

15 typed languages, AI Chat, API Tools, API Schemas and PDF Studio in the latest release.

v10.1 release notes →
::: info Questions? Join the community on [Discord](https://servicestack.net/discord), ask on [GitHub Discussions](https://servicestack.net/ask) or browse the [Live Demos](https://github.com/NetCoreApps/LiveDemos). ::: # Architecture Overview Source: https://docs.servicestack.net/architecture-overview Ultimately behind-the-scenes ServiceStack is just built on top of ASP.NET's Raw [IHttpAsyncHandler](https://msdn.microsoft.com/en-us/library/ms227433.aspx). Existing abstractions and [xmlconfig-encumbered legacy ASP.NET providers](http://mono.servicestack.net/mvc-powerpack/) have been abandoned, in favour of fresh, simple and clean [Caching](/caching), [Session](/auth/sessions) and [Authentication](/auth/authentication-and-authorization) providers all based on clean POCOs, supporting multiple back-ends and all working seamlessly together. Our best-practices architecture is purposely kept simple, introduces minimal new concepts or artificial constructs that can all be eloquently captured in the diagram below: ## Server Architecture ![ServiceStack Logical Architecture View](/img/pages/overview/servicestack-logical-view-02.webp) ## Client Architecture ServiceStack's [Message-based design](/advantages-of-message-based-web-services) allows us to easily support [typed, generic and re-usable Service Clients](/clients-overview) for all our popular formats: ![ServiceStack HTTP Client Architecture](/img/pages/overview/servicestack-httpclients.webp) Having all clients share the same interface allow them to be hot-swappable at run-time without code changes and keep them highly testable where the same unit test can also [serve as an XML, JSON, JSV, SOAP Integration Test](https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.WebHost.IntegrationTests/Tests/WebServicesTests.cs). By promoting clean (endpoint-ignorant and dependency-free) Service and DTO classes, your web services are instantly re-usable and can be hosted in non-http contexts as well. E.g. The client architecture when one of the [built-in MQ Host is enabled](/redis-mq): ![ServiceStack MQ Client Architecture](/img/pages/overview/servicestack-mqclients.webp) # Instantly Servicify existing Systems Source: https://docs.servicestack.net/servicify Most legacy systems don't need a rewrite so much as a **contract**. ServiceStack's [AutoGen](/autoquery/autogen) reads an existing database's schema at startup and generates a complete, typed API over it - Request DTOs, data models, implementations and human-friendly pluralized routes - without migrating a single row. From there the whole framework applies: [instant UIs](/api-explorer), [typed clients in 15 languages](/add-servicestack-reference), [gRPC](/grpc/) and MQ endpoints, declarative validation, authorization and audit history.
Step 1
Register your database
Step 2
Enable GenerateCrudServices
Step 3
You have a typed API
## How it works
Enabling it is a single plugin option - AutoGen inspects the registered connection and registers AutoQuery and CRUD Services for each table it finds: ```csharp services.AddPlugin(new AutoQueryFeature { MaxLimit = 1000, GenerateCrudServices = new GenerateCrudServices { DbFactory = ormLite.DbFactory, } }); ```
::: info Prefer to review the models before they become APIs? [okai TypeScript Data Models](/autoquery/okai-db) takes the other route - export the DB schema to editable TypeScript models first, then generate the APIs, C# data models and migrations from those. ::: ## Your conventions, not just ours AutoGen's code generation is programmatically customizable. Generated types can be augmented with declarative attributes so your App's existing conventions - authorization, validation rules, tags, descriptions, formatting - are baked into the generated Services rather than bolted on afterwards. When the conventions are right, the generated classes can be **ejected** into code-first C# and developed as normal. AutoGen is a way in, not something you're stuck with.
## Reachable from everywhere Because AutoGen produces ordinary ServiceStack Services, they inherit every endpoint and client the framework supports. That makes it the fastest route to putting **gRPC** in front of an existing system - which in turn opens it to [every language in gRPC's protoc universe](https://grpc.io/docs/languages/).
gRPC High-performance endpoints Dart Scriptable protoc clients Flutter Mobile, web & desktop React Native Typed TypeScript DTOs
The [Smart, Generic C# / F# / VB.NET Service Clients](/grpc/generic) still give the best UX for consuming gRPC Services, but the [protoc-generated Dart client](/grpc/dart) is a close second - a high-level language with native-class performance and script-like productivity, which makes it an ideal way to explore a freshly servicified system. And anything Dart reaches, [Flutter](https://flutter.dev) reaches too. ## Modernizing without rewriting This is what makes AutoGen useful beyond greenfield work: it lets you modernize parts of a legacy system incrementally, at low cost. Once a database is behind typed contracts you can enable [Multitenancy](/multitenancy), [Optimistic Concurrency](/ormlite/optimistic-concurrency), [declarative validation](/declarative-validation) and Executable Audit History without changing the schema. Business users can maintain validation rules in the RDBMS and manage them through the [Admin UI](/admin-ui-validation), where they're applied instantly at runtime and surfaced through ServiceStack's [client UI auto-binding options](/world-validation). [Locode](/locode/) then gives stakeholders an instant UI to search their data, export queries to Excel, or work through a custom UI with fine-grained control over which tables and operations each user can reach. ## Next steps
AutoGen docs

Configure, customize and export the generated APIs and data models.

Read the guide →
AutoQuery RDBMS

Understand the queryable APIs AutoGen is generating for each table.

Learn AutoQuery →
Locode database-first

Turn the generated APIs into a branded CRUD App for your stakeholders.

Build the UI →
# ServiceStack v10.5 Source: https://docs.servicestack.net/releases/v10_05
![](/img/pages/release-notes/v10.5/bg.webp) ## New TanStack Start Template We're excited to add a new React template built with [TanStack Start](https://tanstack.com/start/latest), the full-stack React framework from the creators of TanStack Query, Table and Router, as a modern alternative to Next.js for building statically exported React Apps with a .NET backend: :::youtube ic4hiu5Efac TanStack Start + .NET: Type-Safe React Routes, No Node.js Server ::: [![](/img/pages/react/tanstack-static.webp)](https://tanstack-static.react-templates.net)
tanstack-static
Source code on GitHub
tanstack-static.react-templates.net
Live Demo
Like our [next-static](https://github.com/NetCoreTemplates/next-static) template, every page is prerendered to static HTML at build time and served directly by ASP.NET Core, so there's no Node.js server to deploy, run or secure in production - your .NET App is the only thing serving your App. ### Why TanStack Start? - **100% Type-safe Routing** - [TanStack Router](https://tanstack.com/router/latest) generates a fully typed route tree from your file-based routes, so `` paths, path params and search params are all type checked, where renaming or removing a route is a compile error instead of a broken link discovered in production - **Built on Vite** - it's just a Vite plugin, so unlike Next.js it uses the same [Vite+](https://viteplus.dev) toolchain as our other Vite templates for its dev server, HMR and production builds, as well as checking, linting, formatting and testing - **Just React** - no React Server Components, `"use client"` boundaries or server/client component rules to learn. Routes are plain React components, making it simpler to reason about and easier for AI Agents to get right - **Dynamic Routes in Static Exports** - routes with path params like `/posts/$id` are prerendered for every value linked from other pages, with all other values falling back to a generated `_shell.html` SPA shell which renders them in the browser. Next.js static exports instead require every dynamic route value to be known at build time with `generateStaticParams()` - **Prerendered Pages, SPA Navigation** - pages load instantly from prerendered HTML for fast first loads and SEO, then hydrate into a SPA with client-side navigation between pages - **Less Magic, More Explicit** - the `` document, head tags, providers and router are all defined in regular code you own, e.g. per-route page titles and meta tags are declared with a route's `head()` function - **Vendor Neutral** - TanStack Start isn't designed around any hosting platform, and with static prerendering it's deployed as part of your .NET App with the template's existing Docker and [Kamal deployments](https://react-templates.net/docs/deployments) ### Type-safe File-based Routes Pages are added by creating files in `src/routes/` with `createFileRoute()`, e.g. `routes/about.tsx` => `/about` and `routes/posts.$id.tsx` => `/posts/$id`. The route tree is regenerated by `vp dev` and `vp build`, e.g. the auth protected `/profile` page: ```tsx import { createFileRoute } from '@tanstack/react-router' import { appAuth, ValidateAuth } from '@/lib/auth' export const Route = createFileRoute('/profile')({ head: () => ({ meta: [{ title: 'Profile' }] }), // Prerendered as a loading page, the profile is rendered in the browser once the signed-in user is known component: ValidateAuth(Profile), }) function Profile() { const { user, signOut } = appAuth() //... } ``` ### Static Prerendering Static export is configured with the `tanstackStart()` Vite plugin in `vite.config.ts`, which starts from `/` and crawls every linked page, skipping links to pages served by .NET like `/api`, `/ui`, `/admin-ui` and `/Identity`: ```ts tanstackStart({ // Static export: prerender every route to MyApp.Client/dist/client, which is served from MyApp/wwwroot prerender: { enabled: true, crawlLinks: true, // prerender every page linked from a prerendered page autoSubfolderIndex: false, // /about => about.html, served by MapCleanUrls() in Program.cs filter: ({ path }) => !isServerPath(path), // skip links to .NET pages }, // Also write _shell.html, the fallback page for routes not prerendered (e.g. /posts/$id) spa: { enabled: true, maskPath: '/spa-shell', }, }), ``` ### How it works The template uses the same hybrid development model as our other React templates: - **Development** - `dotnet watch` starts both the .NET App and the TanStack Start Vite dev server, with ASP.NET Core proxying page requests to Vite which renders each page on request, with full HMR support - **Production** - `npm run build` prerenders every route to HTML which is published to `MyApp/wwwroot` and served with clean URLs, with any route that wasn't prerendered falling back to `_shell.html` As there's no Node.js server in production, the App calls ServiceStack APIs from the browser with the typed `JsonServiceClient` instead of using TanStack Start server functions, whilst per-user data is fetched in components after hydration. The template's `AGENTS.md` documents these static export rules so AI Agents know which TanStack Start features to use and which to avoid. ## New Astro Template We're also adding a new template built with [Astro](https://astro.build), the web framework for content-driven websites, as an alternative to Next.js for content-first Apps like blogs, docs, marketing and product sites that still need interactive features, ServiceStack APIs and authentication from a .NET backend: :::youtube 1pQ6fe62_s0 Astro + .NET: Static HTML Pages, React Islands, No Node.js Server ::: [![](/img/pages/react/astro-static.webp)](https://astro-static.react-templates.net)
astro-static
Source code on GitHub
astro-static.react-templates.net
Live Demo
Every page is prerendered to static HTML at build time and served directly by ASP.NET Core, so like our other static templates there's no Node.js server to deploy, run or secure in production. ### Why Astro? - **Zero JavaScript by default** - pages are rendered to plain HTML and CSS with no JavaScript shipped to the browser unless a component needs it, giving you small pages, fast first loads and great SEO and Core Web Vitals scores without having to optimize for them - **Islands Architecture** - interactive React components are hydrated as independent "islands" in an otherwise static page, where you choose when each one loads, e.g. `client:load` to hydrate immediately, `client:visible` when scrolled into view or `client:only` to only render in the browser - **Content-first** - Markdown and MDX are first-class pages, whilst [Content Collections](https://docs.astro.build/en/guides/content-collections/) validate each post's frontmatter against a typed schema, so a missing title or invalid date is a build error instead of a broken page - **Just HTML, plus components** - `.astro` components are HTML templates with a frontmatter script that runs at build time, so there are no React Server Components, `"use client"` boundaries or server/client component rules to learn, making pages simpler to reason about and easier for AI Agents to get right - **Built on Vite** - Astro uses Vite for its dev server, HMR and production builds, and the template uses the same [Vite+](https://viteplus.dev) toolchain as our other templates for checking, linting, formatting and testing - **Static by default** - static output is Astro's default rather than an export mode with features to avoid, so there are no unsupported APIs to work around when serving your site from your .NET App - **Batteries included** - official integrations for MDX, RSS feeds, sitemaps and optimized images, with React support provided by the `@astrojs/react` integration, letting you reuse React components and the [@servicestack/react](https://react.servicestack.net) component library - **Vendor Neutral** - Astro isn't designed around any hosting platform, and with static output it's deployed as part of your .NET App with the template's existing Docker and [Kamal deployments](https://react-templates.net/docs/deployments) ### What's included - **Blog** - a Markdown/MDX blog with a typed content collection, an index page, a page per post, an RSS feed at `/rss.xml` and a generated sitemap - **React Islands** - interactive React 19 components calling typed ServiceStack APIs with `JsonServiceClient` - **ASP.NET Core Identity Auth** - sign in, sign up and account management with an auth protected `/profile` page - **Dark Mode** - with a toggle that remembers the user's preference - **AutoQuery CRUD** - the same Bookings AutoQuery APIs as our other templates, which can be managed from the built-in [Admin UI](https://docs.servicestack.net/admin-ui) and explored in the [API Explorer](https://docs.servicestack.net/api-explorer) ### Astro Pages and React Islands Pages are `.astro`, `.md` or `.mdx` files in `src/pages/`, where React components without a `client:*` directive are rendered to static HTML at build time, whilst components with one are hydrated in the browser. For example the home page renders `` as static HTML and hydrates the `` island which calls a ServiceStack API as you type: ```astro --- import { ShellCommand } from 'react-net-templates' import { HelloApi } from '../components/islands' import Layout from '../layouts/Layout.astro' --- npx create-net astro-static MyProject ``` As each island is its own React root, interactive components are wrapped with `withApp()` which provides the ServiceStack `ClientContext` and loads the signed-in user once per page load, so it's shared by every island on the page: ```tsx import { withApp } from '@/lib/app' import HelloApiComponent from './HelloApi' export const HelloApi = withApp(HelloApiComponent) ``` ### How it works The template uses the same hybrid development model as our other templates: - **Development** - `dotnet watch` starts both the .NET App and the Astro dev server, with ASP.NET Core proxying page requests to Astro which renders each page on request. React islands update in place with HMR, whilst changes to `.astro` and Markdown files reload the page - **Production** - `npm run build` prerenders every page to HTML, e.g. `/blog/first-post` => `blog/first-post.html`, which is published to `MyApp/wwwroot` and served with clean URLs, with any unknown path returning the prerendered `404.html` As there's no Node.js server in production, code in an `.astro` file's frontmatter only runs at build time, so per-user data and authenticated APIs are called from React islands in the browser instead. Likewise dynamic routes like `blog/[...slug].astro` need to list every value in `getStaticPaths()` at build time, so data that changes at runtime should be fetched from a ServiceStack API in an island. The template's `AGENTS.md` documents these rules so AI Agents know which Astro features to use and which to avoid. ## React, Next.js & Vue Templates upgraded to Vite+ All our React, Next.js and Vue project templates have been migrated to [Vite+](https://viteplus.dev), the new unified JavaScript toolchain from [VoidZero](https://voidzero.dev) - the team behind Vite, Vitest, Rolldown and Oxc. :::youtube POVYVwCZRYU React, Next.js and Vue on .NET: Unified toolchain with Vite+ ::: Instead of stitching together separate tools, each with their own dependencies, config files and CLIs, Vite+ provides a single `vp` CLI for developing, building, linting, formatting, type checking and testing, all configured from a single `vite.config.ts`: ### Converted Templates The following templates have all been converted to the Vite+ toolchain. Pick one and enter your project name to copy the command to create it, or download it as a ready-to-run .zip: For the Vite-based React and Vue templates, Vite+ also runs the dev server and production build, whilst for the Next.js templates Next.js continues to run the dev server and build, with `vp` used for checking, linting, formatting and testing. ### Why Vite+? - **Much Faster** - Vite+ is built on the Rust-powered [Oxc](https://oxc.rs) and [Rolldown](https://rolldown.rs) toolchain, where Oxlint and Oxfmt are orders of magnitude faster than ESLint and Prettier, and Vite 8's Rolldown bundler replaces both Rollup and esbuild for faster production builds - **One Tool, One Config** - lint, fmt and test configuration all lives in `vite.config.ts`, replacing separate `eslint.config.js`, `vitest.config.ts` and `postinstall` scripts, with a lot fewer `devDependencies` to maintain - **Type-aware Linting & Type Checking** - Oxlint runs type-aware rules powered by TypeScript Go, so `vp check` formats, lints and type checks your entire App in a single pass. The React and Next.js templates have also been upgraded to **TypeScript 7** with no separate `tsc` step, whilst Vue templates use `vue-tsc` to type check `.vue` SFCs - **Consistent Formatting** - all templates are now formatted with Oxfmt, ensuring consistent code style for both humans and AI Agents, with the formatting commit added to `.git-blame-ignore-revs` to keep `git blame` useful - **Simpler CI** - GitHub Actions use [setup-vp](https://github.com/voidzero-dev/setup-vp) to install Node and npm dependencies with caching, and a new `client` job runs `npm run check`, `vp test run` and `npm run build` on every push - **No global install needed** - `vp` is installed locally as a dev dependency so all npm scripts work out-of-the-box, or optionally install the global CLI to run `vp` commands directly: :::copy curl -fsSL https://vite.plus | bash ::: ### Common Commands All templates share the same npm scripts which can be run from the `MyApp.Client` folder: ```bash npm run dev # Start the dev server npm run check # Format + lint + type check npm run lint # Lint with Oxlint npm run fmt # Format with Oxfmt npm run test # Run tests in watch mode npm run test:ui # Run tests with the Vitest UI npm run test:run # Run tests once npm run outdated # Check for outdated dependencies npm run upgrade # Upgrade dependencies ``` ### VS Code Workspace In addition to better tooling and a superior developer experience, every template now also includes a `MyApp.code-workspace` VS Code Workspace. VS Code has become the most popular text editor & IDE for good reason, it's free, cross-platform, has a rich extension ecosystem and has the best support for AI Agents, which are increasingly how new Apps are being built. Open the workspace from **File > Open Workspace from File...** or from the command-line with: :::copy code MyApp.code-workspace ::: The workspace adds the `MyApp.Client` front-end as its own root folder alongside the .NET solution, letting you develop, run and debug both your UI and C#/.NET App from within the same sidebar UI, with each root getting its own tooling: - **Format & Fix on Save** - JS/TS (and `.vue`) files are formatted with Oxfmt and auto-fixed with Oxlint on save, using the same `vite.config.ts` rules as `vp check` and CI, whilst C# and Razor files keep their own formatters - **Recommended Extensions** - VS Code prompts to install the [Vite+ Extension Pack](https://marketplace.visualstudio.com/items?itemName=VoidZero.vite-plus-extension-pack) (Oxc + Vitest), the [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) for .NET, plus [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) for Vue templates or the [TypeScript 7 Native Preview](https://marketplace.visualstudio.com/items?itemName=TypeScriptTeam.native-preview) language server for React & Next.js templates - **Integrated Testing** - run and debug both Vitest front-end tests and NUnit .NET tests from VS Code's Testing sidebar ```json { "folders": [ { "name": "MyApp", "path": "." }, { "name": "MyApp.Client", "path": "MyApp.Client" } ], "settings": { "files.exclude": { "MyApp.Client": true }, "[javascript][javascriptreact][typescript][typescriptreact]": { "editor.defaultFormatter": "oxc.oxc-vscode", "editor.formatOnSave": true, "editor.formatOnSaveMode": "file", "editor.codeActionsOnSave": { "source.fixAll.oxc": "explicit" } } }, "extensions": { "recommendations": [ "VoidZero.vite-plus-extension-pack", "TypeScriptTeam.native-preview", "ms-dotnettools.csdevkit" ] } } ``` ### Updated AI Agent Guidance The `AGENTS.md` instructions in each template have also been updated with the new Vite+ commands, so AI Agents know to use `npm run check` to validate their changes and that `dtos.ts` is automatically regenerated on .NET App startup. ## ServiceStack.Redis This release adds several new features to **ServiceStack.Redis**: - [IDistributedCache & HybridCache](#microsoft-idistributedcache-and-hybridcache) - use ServiceStack.Redis as the Redis backend for ASP.NET Core's caching APIs on .NET 10 - [Redis Streams](#redis-streams-and-consumer-groups) - sync and async Streams APIs, typed JSON entries, consumer groups and pending-message recovery - [Hash field expiration](#hash-field-expiration) - expire individual fields of a hash on Redis 7.4+ or Valkey 9+ - [Atomic key commands](#getex-getdel-and-unlink) - `GETEX`, `GETDEL` and `UNLINK`, plus `UnlinkByPattern` for cleaning up keys without blocking Redis - [Fully async connections](#fully-async-connection-setup) - DNS, TCP, TLS and Redis handshakes no longer block threads in async APIs - [Connection limits](#optional-connection-limits-and-cancellable-pool-waits) - optionally cap `RedisManagerPool` connections and cancel pool waits - [IPv6 and `rediss://` URIs](#ipv6-and-redis-uri-endpoints) - IPv6 hosts and standard Redis URIs with ACL credentials - [Atomic cache expiration](#atomic-cache-expiration-fixes) - fixes `DateTime` and async `TimeSpan` cache expirations - [Reliability fixes](#reliability-and-pipeline-fixes) - safer failover and pipeline timeouts. Empty values in pipelines and transactions [now return `""`](#empty-values-in-pipelines-and-transactions)
Caching upgrades: IDistributedCache, HybridCache L2, atomic expiry, GETEX/GETDEL, UNLINK and hash-field expiry Streams and connection upgrades: Streams, consumer groups, XAUTOCLAIM, MaxLiveConnections, async connect, IPv6 and rediss:// URIs
All new APIs are additive. They're implemented as extension methods over new optional interfaces, so existing `IRedisClient` interfaces don't gain any required members. ::: info Upgrade notes - **Empty values in pipelines and transactions** now return `""` instead of `null`, matching non-queued calls. Set `RedisConfig.PipelineEmptyValuesAsNull = true` to keep the old behavior while you update `== null` checks. See [Empty values in pipelines and transactions](#empty-values-in-pipelines-and-transactions). - **Restricted ACLs**: the new `IDistributedCache` adapter needs permission for both `EVAL` and `EVALSHA`. ::: ### Microsoft IDistributedCache and HybridCache :::youtube bb5ThR6ZV9w Redis Caching in .NET: IDistributedCache, HybridCache and Atomic TTLs ::: On **.NET 10**, ServiceStack.Redis can now back Microsoft's `IDistributedCache`. ASP.NET Core features and libraries that use the standard caching abstractions can then share your Redis client managers. You don't need an extra package. The adapter and its Microsoft dependencies are only included in the `net10.0` build: ```csharp builder.Services.AddServiceStackRedisCache("localhost:6379", options => { options.KeyPrefix = "myapp:cache:v1:"; }); ``` If you already register an `IRedisClientsManager`, the cache can reuse it: ```csharp builder.Services.AddSingleton(c => new RedisManagerPool("localhost:6379")); builder.Services.AddServiceStackRedisCache(); ``` Values are stored as raw bytes, so empty values are kept as is. Absolute and sliding expiration are both supported. Get, Set and Refresh each run as an atomic Lua script, which means a refresh can never push an entry past its absolute expiration. It also works as the distributed L2 cache for Microsoft's [HybridCache](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/hybrid): ```csharp builder.Services.AddServiceStackRedisCache("localhost:6379"); builder.Services.AddHybridCache(); ```
Two app servers, each with its own in-process HybridCache L1, sharing Redis as the distributed L2 byte storage
The scripts are cached on the server and run by their SHA1 hash, so each call sends only the arguments. It requires Redis 5+ (or Valkey) with permission to run `EVAL` and `EVALSHA`. See the [IDistributedCache docs](/redis/distributed-cache) for manager ownership, expiration rules and the required ACL permissions. ### Redis Streams and Consumer Groups ServiceStack.Redis now supports [Redis Streams](https://redis.io/docs/latest/develop/data-types/streams/). It has sync and async APIs for appending, reading, trimming and deleting entries, and consumer group APIs for reading, acknowledging, inspecting and reclaiming pending messages. :::youtube RhNCEMj1gQA Build a Redis Streams Work Queue in C# That Survives Worker Crashes ::: The typed APIs store your POCO as JSON, so a work queue takes only a few lines: ```csharp // One-time setup: create the consumer group (and stream if it doesn't exist) await redis.XGroupCreateAsync("orders", "workers", makeStream: true, token: token); string id = await redis.AddStreamEntryAsync("orders", new OrderEvent { OrderId = 1 }, token: token); var entries = await redis.ReadStreamGroupEntriesAsync("workers", "worker-1", new[] { new RedisStreamPosition { Stream = "orders", Id = ">" } }, count: 100, blockMilliseconds: 1000, token: token); foreach (var entry in entries) { if (!entry.HasValue) continue; await ProcessOrder(entry.Value); await redis.XAckAsync("orders", "workers", new[] { entry.Id }, token); } ``` Messages are only acknowledged when you call `XAck`. Messages from a consumer that crashed stay pending until another worker claims them with `XAutoClaim`. A message can be delivered more than once, so handlers should be idempotent.
worker-2 crashes mid-order and its two messages stay in the pending list, unacknowledged XAutoClaim moves the idle pending messages to worker-3; claiming does not acknowledge them
Use `AddStreamEntries` to append many entries at once. It sends them in pipelined batches and returns the generated IDs in input order: ```csharp string[] ids = await redis.AddStreamEntriesAsync("orders", orderEvents, batchSize: 100, maxLength: 10_000, token: token); ``` Bulk appends are pipelined, not atomic: if a batch fails, earlier batches stay in the stream, so include your own event ID when you need to retry safely.
Batches 1 and 2 are appended, batch 3 fails and the rest are never sent; a blind retry appends batches 1 and 2 twice
`XAdd`, `XAck`, `XDel`, `XTrim` and `XLen` can also be queued in Redis pipelines. Streams require Redis 5+, and `XAutoClaim` requires Redis 6.2+. See the [Redis Streams docs](/redis/streams) for the native byte APIs, pending-message recovery and failure semantics. ### Hash Field Expiration Redis 7.4 added expiration for individual hash fields, and ServiceStack.Redis now supports it with sync and async APIs. You can keep related values together in one hash while letting each field expire on its own schedule, e.g. a user's online presence or a short-lived one-time code: ```csharp await redis.SetEntryInHashAsync("users:42", "presence", "online", token); long[] results = await redis.HPExpireAsync("users:42", 30_000, new[] { "presence", "missing" }, RedisHashExpiryCondition.NX, token); // [1, -2]: "presence" now expires in 30s, "missing" doesn't exist ``` | API | Redis Command | Description | |-|-|-| | `HExpire` / `HPExpire` | `HEXPIRE` / `HPEXPIRE` | Expire fields after a number of seconds / milliseconds | | `HExpireAt` / `HPExpireAt` | `HEXPIREAT` / `HPEXPIREAT` | Expire fields at a Unix timestamp | | `HTtl` / `HPTtl` | `HTTL` / `HPTTL` | Get each field's remaining time to live | | `HExpireTime` / `HPExpireTime` | `HEXPIRETIME` / `HPEXPIRETIME` | Get each field's expiration timestamp | | `HPersist` | `HPERSIST` | Remove each field's expiration | Each API returns one status code per field, in the order you passed them, so you can tell which fields were updated, which were missing and which were skipped by a `NX`, `XX`, `GT` or `LT` condition. Expiring a field doesn't change the TTL of the hash itself.
users:42 keeps name and email forever while only its presence field expires in 30 seconds, with a status code per field
Hash field expiration requires Redis 7.4+ or Valkey 9+. These commands can't be queued in pipelines or transactions yet. See [Hash Field Expiration](/redis/hash-field-expiration) for the status codes and the binary APIs. ### GETEX, GETDEL and UNLINK New sync and async APIs for Redis's atomic key commands: | API | Redis Command | Description | |-|-|-| | `GetAndExpireValue` | `GETEX` | Return a value and update its expiration in one command | | `GetAndDeleteValue` | `GETDEL` | Return a value and delete it in one command | | `Unlink` | `UNLINK` | Remove keys immediately, freeing their memory in the background | ```csharp using var redis = redisManager.GetClient(); string value = redis.GetAndExpireValue("session:1", new RedisGetExOptions { ExpirySeconds = 60 }); string token = redis.GetAndDeleteValue("one-time-token:1"); long removed = redis.Unlink("large:key", "another:key"); ```
Two requests run GETDEL on the same one-time token at the same moment: one gets the token, the other gets null UNLINK removes a large key immediately and reclaims its memory in the background while other commands keep running
`RedisGetExOptions` can set a relative or absolute expiration, or remove it with `Persist = true`. If you don't pass any options, the key keeps its existing TTL. `GETEX` and `GETDEL` require Redis 6.2+. #### Pattern Cleanup with SCAN + UNLINK `UnlinkByPattern` removes every key matching a pattern in bounded `UNLINK` batches. Because it uses `SCAN` instead of `KEYS`, it doesn't block Redis while it runs: ```csharp long removed = await redis.UnlinkByPatternAsync("cache:reports:*", batchSize: 512, token: token); ```
UnlinkByPattern walks the keyspace with SCAN and removes keys in bounded UNLINK batches, interleaved with other clients' commands
The existing `RemoveByPattern` behavior is unchanged. See [atomic key commands](/redis/client#atomic-key-commands) for details. ### Fully Async Connection Setup The async APIs previously had to make blocking calls while opening a new connection. Now each step of opening a connection is async: DNS lookup, TCP connect, TLS handshake, `AUTH`, `SELECT`, `CLIENT SETNAME` and the initial server discovery. Resetting the database on a pooled client no longer happens while holding the pool lock either. Under load this means fewer blocked thread pool threads. ```csharp using var pool = new RedisManagerPool("localhost:6379?ConnectTimeout=2000"); await using var redis = await ((IRedisClientsManagerAsync)pool).GetClientAsync(token); ```
DNS, TCP, TLS, AUTH, SELECT and INFO each run asynchronously under one ConnectTimeout deadline
`ConnectTimeout` now acts as one deadline for the entire async connection setup, and the `CancellationToken` you pass in can abort it at any step. A new `ConnectionFilterAsync` hook on clients and managers lets you run your own async setup on each new connection: ```csharp pool.ConnectionFilterAsync = async (client, token) => await client.PingAsync(token); ``` Existing synchronous hooks, custom resolvers and Sentinel discovery behave the same as before. See [async connection setup](/redis/async#fully-async-connection-setup) for details. ### Optional Connection Limits and Cancellable Pool Waits By default, `RedisManagerPool` creates extra connections whenever its pool is exhausted. If you need to stay within a Redis server's connection limit, you can now set `MaxLiveConnections` to cap them:
By default a spike opens overflow connections past the retained pool, toward your Redis plan's connection limit
```csharp using var pool = new RedisManagerPool("localhost:6379", new RedisPoolConfig { MaxPoolSize = 20, // Clients kept for reuse MaxLiveConnections = 40, // Max open connections at any one time MaxWaitingClients = 100, // Max callers waiting for a free connection (0 = fail fast) PoolTimeout = 2000, // Max time in ms to wait for a free connection }); ``` When the limit is reached, callers wait for a free connection and fail with a `TimeoutException` if none frees up within `PoolTimeout`. When the wait queue is also full, they fail immediately. Sync and async callers share the same limit, and `GetStats()` includes the new admission counters. If you leave `MaxLiveConnections` unset, the pool keeps its existing behavior.
At MaxLiveConnections, callers wait in a queue up to MaxWaitingClients for PoolTimeout, or fail fast
`PooledRedisClientManager` and `RedisManagerPool` now also stop waiting for a free client when the `CancellationToken` passed to `GetClientAsync()` is cancelled. Waiting callers, sync or async, are served in the order they arrived: each returned client wakes only the next waiter, while failover and disposal wake them all: ```csharp using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2)); await using var redis = await ((IRedisClientsManagerAsync)redisManager).GetClientAsync(cts.Token); ``` See [bounded admission](/redis/client-managers#optional-bounded-admission) for the full behavior. ### IPv6 and Redis URI Endpoints Connection strings now accept IPv6 addresses (in brackets, e.g. `[::1]:6379`) and hosts that resolve to both IPv4 and IPv6 addresses, trying IPv4 addresses first. They also accept standard `rediss://` TLS URIs, with URL-encoded ACL credentials and an optional database number: ```csharp using var redis = new RedisClient("rediss://user:p%40ss@redis.example:6380/2"); // Parse a redis:// URI as a standard Redis URI: var endpoint = RedisEndpoint.ParseUri("redis://user:p%40ss@[::1]:6379/2"); ```
An IPv6 literal [::1]:6379 and a rediss:// URI with TLS, ACL user, URL-encoded password and database number
Existing `redis://` connection strings are parsed the same way as before. Call `RedisEndpoint.ParseUri` to parse them as standard Redis URIs. See [IPv6 and Redis URIs](/redis/client-managers#ipv6-and-opt-in-redis-uri-endpoints). ### Atomic Cache Expiration Fixes The `ICacheClient` `Set`, `Add` and `Replace` overloads that take a `DateTime` expiration now write the value and its expiration in one atomic operation. Before, they used two separate commands, so a concurrent write or a dropped connection could leave a key with the wrong expiration, or none at all. These overloads use `SET PXAT` on Redis 6.2+ and fall back to an atomic Lua script on older servers.
In v10.4, SET and PEXPIREAT were separate commands: a dropped connection between them left the key with no expiry In v10.5, one SET key value PXAT command writes the value and its expiry together, with a Lua fallback for older servers
The async `AddAsync` and `ReplaceAsync` overloads that take a `TimeSpan` also failed to pass their expiration to Redis, so keys were stored without a TTL. They now set the expiration the same way as their sync versions. ### Reliability and Pipeline Fixes This release also includes several reliability fixes for connection pools and pipelines: - **Failover** - pools no longer hand out a client that was created or reset against the old master during a failover; they retry against the new hosts instead. A failed acquisition can't release another caller's reserved pool slot. - **Custom resolvers** - subclasses that override `RedisResolver.CreateRedisClient` keep applying their credentials, TLS and routing when clients are acquired with `GetClientAsync()`. - **Pipeline timeouts** - async pipelines (including `AddStreamEntries`) now honor `SendTimeout` when sending and `ReceiveTimeout` for each reply. On timeout, cancellation or a malformed reply the connection is closed, so unread replies can't be returned as the result of a later command. - **Partial sends** - sync and async sends now finish writing commands when the socket only accepts part of the buffer. - **IPv6 fallback** - hostnames try their IPv4 addresses first, then IPv6, so hosts reachable over IPv4 connect exactly as before and IPv6-only hosts now work. With a `ConnectTimeout`, each attempt gets a share of it, so an unreachable address can't use up the whole timeout before the next one is tried.
Failover no longer hands out clients from the old master, and async pipelines honor SendTimeout and ReceiveTimeout
#### Empty values in pipelines and transactions Reading an empty string or byte array in a pipeline or transaction now returns the empty value instead of `null`, matching what the same call returns outside a pipeline. Missing keys still return `null`: ```csharp redis.SetValue("key", ""); redis.GetValue("key"); // "" (unchanged) string value = null; using var trans = redis.CreateTransaction(); trans.QueueCommand(r => r.GetValue("key"), v => value = v); trans.Commit(); // value: was null, now "" ```
A queued read of an empty value returned null in v10.4 and returns
This applies to every queued string and byte read, e.g. `GetValue`, `GetValueFromHash` and list pops. If you check results from a pipeline or transaction with `value == null`, use `string.IsNullOrEmpty(value)` to keep treating empty values as missing. Queued reads into an `int` still return `0` for an empty value. To keep the previous behavior while you update your code, turn it back on at startup: ```csharp RedisConfig.PipelineEmptyValuesAsNull = true; ``` See [Redis async APIs](/redis/async) and [client managers](/redis/client-managers) for more information. # Release Notes History Source: https://docs.servicestack.net/release-notes-history ## 2026 - [v10.5](/releases/v10_05) - [v10.4](/releases/v10_04) - [v10.3](/releases/v10_03) - [v10.2](/releases/v10_02) - [v10.1](/releases/v10_01) ## 2025 - [v10](/releases/v10_00) - [v8.10](/releases/v8_10) - [v8.9](/releases/v8_09) - [v8.8](/releases/v8_08) - [v8.7](/releases/v8_07) - [v8.6](/releases/v8_06) ## 2024 - [v8.5](/releases/v8_05) - [v8.4](/releases/v8_04) - [v8.3](/releases/v8_03) - [v8.2](/releases/v8_02) - [v8.1](/releases/v8_01) ## 2023 - [v8](/releases/v8_00) - [v6.11](/releases/v6_11) - [v6.10](/releases/v6_10) - [v6.9](/releases/v6_09) - [v6.8](/releases/v6_08) - [v6.7](/releases/v6_07) - [v6.6](/releases/v6_06) ## 2022 - [v6.5](/releases/v6_05) - [v6.4](/releases/v6_04) - [v6.3](/releases/v6_03) - [v6.2](/releases/v6_02) - [v6.1](/releases/v6_01) - [v6](/releases/v6_00) ## 2021 - [v5.13](/releases/v5_13) - [v5.12](/releases/v5_12) - [v5.11](/releases/v5_11) ## 2020 - [v5.10](/releases/v5_10) - [v5.9](/releases/v5_9) - [v5.8](/releases/v5_8) ## 2019 - [v5.7](/releases/v5_7) - [v5.6](/releases/v5_6) - [v5.5](/releases/v5_5) ## 2018 - [v5.4](/releases/v5_4) - [v5.2](/releases/v5_2) - [v5.1.0](/releases/v5_1_0) - [v5.0.2](/releases/v5_0_0) ## 2017 - [v5.0.0](/releases/v5_0_0#v5-release-notes) - [v4.5.14](/releases/v4_5_14) - [v4.5.10](/releases/v4_5_10) - [v4.5.8](/releases/v4_5_8) - [v4.5.6](/releases/v4_5_6) ## 2016 - [v4.5.2](/releases/v4_5_2) - [v4.5.0](/releases/v4_5_0) - [v4.0.62](/releases/v4_0_62) - [v4.0.60](/releases/v4_0_60) - [v4.0.56](/releases/v4_0_56) - [v4.0.54](/releases/v4_0_54) - [v4.0.52](/releases/v4_0_52) ## 2015 - [v4.0.50](/releases/v4_0_50) - [v4.0.48](/releases/v4_0_48) - [v4.0.46](/releases/v4_0_46) - [v4.0.44](/releases/v4_0_44) - [v4.0.42](/releases/v4_0_42) - [v4.0.40](/releases/v4_0_40) - [v4.0.38](/releases/v4_0_38) - [v4.0.36](/releases/v4_0_36) ## 2014 - [v4.0.35](/releases/v4_0_35) - [v4.0.34](/releases/v4_0_34) - [v4.0.33](/releases/v4_0_33) - [v4.0.32](/releases/v4_0_32) - [v4.0.31](/releases/v4_0_31) - [v4.0.30](/releases/v4_0_30) - [v4.0.24](/releases/v4_0_24) - [v4.0.23](/releases/v4_0_23) - [v4.0.22](/releases/v4_0_22) - [v4.0.21](/releases/v4_0_21) - [v4.0.19](/releases/v4_0_19) - [v4.0.18](/releases/v4_0_18) - [v4.0.15](/releases/v4_0_15) - [v4.0.12](/releases/v4_0_12) - [v4.0.11](/releases/v4_0_11) - [v4.0.10](/releases/v4_0_10) - [v4.0.09](/releases/v4_0_09) - [v4.0.08](/releases/v4_0_08) - [v4.0.06](/releases/v4_0_06) - [v4.0.0](/releases/v4_0_0) ## 2013 and prior - [Older v3 Release Notes](/release-notes-v3) # Pre Release NuGet Packages Source: https://docs.servicestack.net/pre-release ## ServiceStack Pre-Release NuGet Packages Our interim pre-release NuGet packages in between major releases on NuGet are published to [Feedz.io](https://feedz.io/). ::: tip If preferred, the pre-release packages are also available in our [MyGet](/myget) or [GitHub Packages Registry](/gh-nuget) ::: ### Add using Mix If you have the [dotnet x tool](/dotnet-tool) installed, you can configure your projects by downloading `NuGet.Config` in the same folder as your **.sln** :::sh npx add-in feedz ::: ### Add using VS .NET Instructions to add ServiceStack's Pre-Release packages feed to VS .NET are: 1. Go to **Tools** > **Options** > **Nuget Package Manager** > **Package Sources** 2. Add the Source `https://f.feedz.io/servicestack/pre-release/nuget/index.json` with the name of your choice, e.g. `ServiceStack Pre-Release` After registering the feed it will show up under NuGet package sources when opening the NuGet package manager dialog: ![NuGet Package Manager](https://raw.githubusercontent.com/ServiceStack/Assets/master/img/wikis/myget/package-manager-ui.png) Which will allow you to search and install pre-release packages from the selected Pre Release packages feed. ### Adding Pre-Release NuGet feed without VS .NET If you're not using or don't have VS .NET installed, you can add the MyGet feed to your NuGet.config at `%AppData%\NuGet\NuGet.config`: ```xml ``` ## Redownloading Pre Release packages If you've already packages with the **same version number** from Feedz previously installed, you will need to manually delete the NuGet `/packages` folder for NuGet to pull down the latest packages. ### Clear NuGet Package Cache You can clear your local NuGet packages cache in any OS by running the command-line below in your favorite Terminal: :::sh nuget locals all -clear ::: If `nuget` is not in your Systems `PATH`, it can also be invoked from the `dotnet` tool: :::sh dotnet nuget locals all --clear ::: Within VS .NET you can clear them from **Tools** > **Options** > **Nuget Package Manager** and click **Clear All NuGet Cache(s)**: ![Clear Packages Cache](https://raw.githubusercontent.com/ServiceStack/Assets/master/img/wikis/myget/clear-package-cache.png) Alternatively on Windows you can delete the Cached NuGet packages manually with: :::sh del %LOCALAPPDATA%\NuGet\Cache\*.nupkg /q ::: ### Full Package Clean In most cases clearing the NuGet packages cache will suffice, sometimes you'll also need to manually delete other local packages caches delete all NuGet packages in `/packages` folder: :::sh rd /q /s packages ::: delete `/bin` and `/obj` folders in host project :::sh rd /q /s bin obj ::: ## Versioning Scheme ::include versioning-scheme.md:: # Supplier Security Assurance Source: https://docs.servicestack.net/security/supplier-assurance [Security overview](/security/) · [Information security policy](/security/information-security-policy) · [CRA readiness](/security/cra) This page maps common supplier security questions to ServiceStack's public policies, product evidence and current assurance status. The materials are provided in English. Identify the package IDs, exact versions and deployment scope before using evidence in an assessment. Last reviewed: **13 November 2026**. ## Assurance evidence directory | Review topic | Public evidence and current position | | --- | --- | | Information security policy | [Public policy summary](/security/information-security-policy), including scope, accountability, information handling and review. | | Security and privacy certifications | ServiceStack has not obtained independent organizational security or privacy certifications such as ISO 27001 or SOC 2. No certificate or ISO Statement of Applicability is supplied. A service provider's certification is not a ServiceStack certification. | | Independent information security audits | No independent organizational security-controls audit report is available in this evidence set. [Internal product review evidence](/security/assessments) has a different scope. | | Penetration tests, vulnerability assessments and remediation | [Assessment evidence](/security/assessments) identifies the published internal review and current penetration-test report availability. No blanket statement that all high/critical findings have been mitigated is supplied. | | Incident detection, response and recovery capabilities | [Application security guides](/security/application-security) describe configurable logging and security features. [Reporting and disclosure](/security/reporting) describes product vulnerability handling. These libraries are not a managed incident-response service; see the responsibility boundaries below. | | Open-source and software supply-chain risks | All package source and its complete commit history are public. Packages are built and published to NuGet.org by public GitHub Actions workflows using NuGet Trusted Publishing, with Source Link commit metadata and hash-matched release evidence. See [open source and verifiable publishing](/security/secure-development#open-source-and-verifiable-publishing), plus dependency selection and advisory monitoring. | | Vulnerability disclosure programme | [Private reporting and coordinated disclosure](/security/reporting), the [published disclosure policy](https://servicestack.net/security) and [public advisories](https://github.com/ServiceStack/ServiceStack/security/advisories). | | NIS2 | See [NIS2 applicability](#nis2-applicability). No organization-wide NIS2 compliance assertion is supplied. | | EU AI Act | See [EU AI Act applicability](#eu-ai-act-applicability). No blanket AI Act compliance assertion is supplied for all products or uses. | | CE marking | [CRA readiness and CE-marking position](/security/cra). The planned approach is to apply marking where legally required after the applicable conformity work; current CRA conformity is not asserted. | | Software Bill of Materials | [Version-specific SBOM downloads and verification](/security/sbom-vex). Check the included package mapping, release version and framework coverage. | | VEX and ongoing updates | [Reviewed VEX availability and interpretation](/security/sbom-vex#vex-information). Reviewed statements are included when available; an absent VEX file is not an all-clear. No unconditional per-release VEX or LTS maintenance commitment is established. | | Secure software development lifecycle | [Development process and inspectable evidence](/security/secure-development). This describes the documented process; it is not an independently certified SDLC or a claim of complete NIST SSDF or IEC 62443-4-1 conformance. | | Support, termination and end of life | [Security updates and support](/security/support) explains update guidance, residual-risk considerations and the status of formal product security-support schedules. | ## Product and service responsibility boundaries ServiceStack developer libraries run within the integrating application's environment. The application operator controls deployment, authentication configuration, tenant authorization, logging, monitoring, backups and recovery. Product capabilities must be configured and tested in that environment; their availability does not establish an operational security service. No managed incident-response SLA, application recovery time objective (RTO) or recovery point objective (RPO) is provided by these library assurance pages. A disclosure acknowledgement target is not an incident-resolution or recovery guarantee. Separate hosted services or contractual services require their own scoped assessment. ## NIS2 applicability NIS2 applicability requires an entity-level assessment of the services provided, relevant sector, size, jurisdiction and applicable national implementation. A customer's regulated status does not, on its own, determine a software supplier's status. Supply-chain requirements may also be relevant to the customer's review. See the [European Commission's NIS2 guidance](https://digital-strategy.ec.europa.eu/en/policies/nis2-directive). ServiceStack's entity-level applicability assessment remains under review. These pages provide scoped product and security-practice evidence, rather than an organization-wide NIS2 compliance declaration or an unsupported out-of-scope conclusion. ## EU AI Act applicability AI Act obligations depend on the actual system or model, intended purpose and the organization's role. See the [European Commission's AI Act guidance](https://digital-strategy.ec.europa.eu/en/policies/regulatory-framework-ai) and the [AI Act legal text](https://eur-lex.europa.eu/eli/reg/2024/1689). An inventory of general-purpose serialization, contracts or data-access libraries does not establish that an AI system or model is supplied. Equally, that observation does not determine the status of ServiceStack's separate AI features, third-party model integrations, an integrating application's AI functionality or internal AI-assisted development. Those uses require separate assessment. No product-wide or organization-wide AI Act conformity claim is made by this security evidence set. ## Disclosure and evidence handling The linked public summaries, source reports, advisories and versioned release bundles are the standard self-service assurance materials. Internal infrastructure inventories, credentials, personal information, undisclosed exploit details and raw investigation records are confidential and are not included in public bundles. Where evidence is unavailable, this page states that limitation; confidentiality is not used to imply that an unpublished certificate, test or completed assessment exists. Any additional sharing of sensitive evidence requires a scoped review. Retain the documents, package versions, source revisions, checksums and review date used for your assessment. The publication of a policy or inventory is not proof that every control has been independently audited or that a customer's integrated product is compliant. # Information Security Policy Source: https://docs.servicestack.net/security/information-security-policy [Security overview](/security/) · [Supplier assurance](/security/supplier-assurance) · [Secure development](/security/secure-development) This is the public summary of ServiceStack's existing management-approved information security policy and related information-handling practices. It provides supplier-shareable policy information without disclosing internal access records, operational procedures or infrastructure details. It does not adopt unapproved CRA policy extensions or establish an independent certification. | Policy information | Details | | --- | --- | | Policy owner and approval responsibility | ServiceStack CEO | | Public summary version | 1.0 | | Public summary published and reviewed | 13 November 2026 | | Policy review | Annually and when material changes require an update | | Scope | ServiceStack employees, contractors and third parties with authorized access to company systems, information or software-development assets | The publication date identifies this summary; it is not a retrospective effective date for every described control. ## Purpose and accountability ServiceStack's policy is to protect the confidentiality, integrity and availability of company information and the integrity of its software development and distribution. The CEO is responsible for policy approval and security decisions. Personnel with access to source, release systems or customer information are responsible for protecting that access and raising security concerns. ## Access and authentication Access is limited to what a person's role requires. Public read access to source code does not grant permission to modify repositories, publish packages or access operational systems. Contributor and operational access is restricted, and access is updated or revoked when responsibilities change or a person leaves. Strong authentication, private-key access and multi-factor authentication are used for sensitive systems where supported. Credentials, private keys and publishing secrets must not be included in public source, issue reports or support examples. This summary does not assert that all access controls have undergone an independent audit. ## Information handling and privacy Customer information is limited to what is needed for purchasing, licensing, account administration and support. Payment processing is handled through Stripe. Access to customer information is restricted to personnel who need it for their work. See the [ServiceStack privacy policy](https://servicestack.net/privacy) for public privacy information. Use minimal, sanitized reproductions for support and security reports. Remove credentials, personal data and unrelated confidential information before sharing. Sensitive information should not be posted in public repositories or forums. Use private reporting channels for suspected vulnerabilities. Company services use protected transmission channels such as TLS and SSH. Internal access details and security investigation material are not public supplier evidence. ## Software development and supply chain All product source code, its complete change history and the build and release workflows are public. Packages are published to NuGet.org only through those public workflows using NuGet Trusted Publishing, without a stored publishing API key. Changes are subject to maintainer review and automated testing through the development process. Dependency selection favors a small dependency set, with advisory monitoring and updates; a dependency's publisher does not exempt it from review. Configured packages have automated, version-specific SBOM generation and release-evidence verification. See [secure development and supply-chain practices](/security/secure-development) for the actual workflow, coverage and limitations. Source visibility and automated checks complement review; they do not establish that all vulnerabilities have been found. ## Security reports and incidents Suspected product vulnerabilities must be reported privately using the [published reporting channels](/security/reporting). The [disclosure policy](https://servicestack.net/security) defines reporting scope, response targets and coordinated disclosure. It supersedes older instructions that directed vulnerability reports to public issue trackers. Reports are assessed for affected products and versions, impact, remediation and appropriate communication. Published advisories identify affected versions, available fixes and mitigations. Applicable regulatory reporting is a separate responsibility from researcher acknowledgement and public disclosure. ## Continuity and recovery Operational continuity and evidence preservation support the development, distribution and maintenance of products. Public source history and package availability are useful records, but do not establish that recovery has been tested. This policy summary makes no measured recovery-time or recovery-point commitment; integrating applications need their own backup and recovery arrangements. ## Review and assurance Policy changes are reviewed under the CEO's responsibility and communicated to relevant personnel. Public evidence is maintained through this security section, release records and advisories. Internal control records and confidential investigation details are not published by this summary. See [supplier assurance](/security/supplier-assurance) for certification and audit availability, and [CRA readiness](/security/cra) for work still under assessment. The public information security policy, product disclosure policy and future product conformity declarations have different purposes and should be assessed separately. # SBOM and VEX Downloads Source: https://docs.servicestack.net/security/sbom-vex [Security Assurance](/security/) · [Security Assessments](/security/assessments) · [CRA and CE Marking](/security/cra) ServiceStack's security bundles provide machine-readable software inventories and supporting evidence for identified NuGet releases. Downloading these files does not require a ServiceStack subscription. ## Download a release bundle Open the [ServiceStack GitHub releases](https://github.com/ServiceStack/ServiceStack/releases), select the release matching your packages, and expand **Assets**. When generation has completed successfully, the release includes: - `servicestack-security-.zip` - `servicestack-security-.zip.sha256` A release tag such as `v10.4` maps to NuGet version `10.4.0`. A patch tag such as `v10.4.2` maps to `10.4.2`. ### Verified download: 10.5.0 The following files were verified on **14 November 2026**: - [Download the 10.5.0 security ZIP](https://github.com/ServiceStack/ServiceStack/releases/download/v10.5/servicestack-security-10.5.0.zip) - [Download its SHA-256 checksum](https://github.com/ServiceStack/ServiceStack/releases/download/v10.5/servicestack-security-10.5.0.zip.sha256) - [View the originating security workflow](https://github.com/ServiceStack/ServiceStack/actions/runs/43396620198) This bundle contains 49 package release records, all for 10.5.0. Its provenance identifies the exact published NuGet archives as the source and the dependency graph as a consumer baseline resolved at generation time. ### Verified download: 10.4.2 The following files were verified on **12 November 2026**: - [Download the 10.4.2 security ZIP](https://github.com/ServiceStack/ServiceStack/releases/download/v10.4.2/servicestack-security-10.4.2.zip) - [Download its SHA-256 checksum](https://github.com/ServiceStack/ServiceStack/releases/download/v10.4.2/servicestack-security-10.4.2.zip.sha256) - [View the originating security workflow](https://github.com/ServiceStack/ServiceStack/actions/runs/39264297239) This bundle contains 49 package release records, all for 10.4.2. Its provenance identifies the exact published NuGet archives as the source and the dependency graph as a consumer baseline resolved at generation time. Security generation runs separately after NuGet Pack. NuGet Publish waits for matching evidence, verifies it against the packed archives, and retains it after publishing. A subsequent attachment job prepares the public ZIP and attaches it to the matching release, or creates a versioned draft with the assets ready. Release publication and manual reattachment reuse that evidence without waiting for NuGet indexing. A published package or release does not by itself establish that attachment has completed successfully. If an asset is absent or its generation failed, there is no matching published bundle at that location yet. Check [release-security workflow results](https://github.com/ServiceStack/ServiceStack/actions/workflows/release-security.yml); do not substitute a different release's inventory. ## What is in the ZIP? The archive preserves the source-project folder layout. Start with the files at its root: | File | Purpose | | --- | --- | | `README.md` | Scope and interpretation guidance | | `index.json` | Included package IDs, versions, NuGet archive hashes and framework coverage | | `packages.json` | Package-to-project mapping for the evidence set | | `source-run.json` | Source release/build, workflow and tooling provenance | | `publication.json` | NuGet Publish run and its matching pack provenance, in bundles produced by the build-to-release flow | | `SHA256SUMS` | Checksums for the enclosed evidence files | Each package has a `security/releases//` folder containing: | File or folder | Purpose | | --- | --- | | `sbom.cdx.json` | CycloneDX 1.6 JSON inventory combining the package's shipped target-framework graphs | | `manifest.json` | Original NuGet archive SHA-256, evidence hashes, framework coverage, generator details and limitations | | `resolution.json` | Declared dependency ranges and exact resolved dependency graphs | | `audit.json` | Managed NuGet advisory observation at generation time | | `vex/` | Dated reviewed vulnerability-impact statements, when available | | `scans/` | Subsequent advisory observations, if included in that evidence set | Framework-specific graph references distinguish dependency applicability within the combined SBOM. Repeated NuGet package identities across frameworks are intentional. Native payload hashes are inventoried where present; a hash alone does not establish the embedded engine version or its vulnerability status. ## Verify integrity Download the ZIP and checksum into the same folder. On Linux: ```sh sha256sum -c servicestack-security-10.5.0.zip.sha256 unzip servicestack-security-10.5.0.zip -d servicestack-security-10.5.0 cd servicestack-security-10.5.0 sha256sum -c SHA256SUMS ``` On macOS, use `shasum -a 256 -c` in place of `sha256sum -c`. On Windows, compare `Get-FileHash -Algorithm SHA256` with the published checksum. The per-package manifest also identifies the original `.nupkg` hash, allowing you to compare the inventory with the package you obtained. Checksums detect content changes; they are not a digital signature or independent security attestation. ## VEX information VEX describes an assessed vulnerability's impact on specified product versions and framework variants. ServiceStack renders dated CycloneDX VEX snapshots only when vulnerability-specific reviewed decisions are available. These can identify an affected, fixed, under-investigation or justified not-affected state. **The absence of VEX means no reviewed statements are included; it does not mean the product has no vulnerabilities.** The verified 10.5.0 and 10.4.2 public bundles contain no VEX snapshots. Do not infer a not-affected decision from an empty decisions list or a scanner returning no matches. Where a release contains several VEX snapshots, use the most recent applicable assessment and retain the earlier snapshots for history. Read the advisory, affected references, analysis, justification and remediation guidance together. A statement about one release or framework is not a statement about all ServiceStack products or all downstream configurations. There is no blanket commitment on this page to publish VEX with every release or to maintain an unspecified LTS branch. Applicability depends on the vulnerability assessment and the supported product/version concerned. ## Advisory observations and downstream scope `audit.json` is a point-in-time observation from NuGet advisory data, not a continuously updated all-clear. The [scheduled security workflow](https://github.com/ServiceStack/ServiceStack/actions/workflows/security-core.yml) rescans retained release graphs against current advisory data and preserves observations, including findings. Historical graphs can gain new advisory matches without their original SBOM changing. Customers should scan their own application's resolved dependency graph and track .NET, operating-system, container and native-engine advisories separately. These package observations do not assess all first-party ServiceStack code or every deployment configuration. ## Build and pre-release evidence For evidence associated with a particular package build, open its linked [Package Security Evidence workflow run](https://github.com/ServiceStack/ServiceStack/actions/workflows/package-security.yml). Its **Artifacts** section can include: - **ServiceStack Security** — the evidence tree; - **ServiceStack Security ZIP** — a compressed bundle and checksum. Use `source-run.json` to match the security output to its originating pack run and commit, and the manifests to match the actual NuGet archives. GitHub Actions artifact downloads require GitHub sign-in and are retained for 90 days. Public release assets provide the direct download route for released evidence. SBOMs are distributed separately; they are not currently embedded inside the `.nupkg` downloaded from NuGet or MyGet. Reattaching a release ZIP reuses the retained publication evidence; it does not rerun dependency resolution or perform a new vulnerability assessment. Regenerating source evidence or adding reviewed VEX is a separate operation. Earlier release bundles may have been generated directly from NuGet, as their provenance states. Record the download date, checksum and provenance when retaining evidence for your own review. Actions retention still applies: if the original publication evidence has expired or is unavailable, reattachment fails explicitly rather than substituting another version or a fresh graph. # Security Assessments and Testing Evidence Source: https://docs.servicestack.net/security/assessments [Security Assurance](/security/) · [SBOM and VEX Downloads](/security/sbom-vex) · [CRA and CE Marking](/security/cra) This page identifies published assessment evidence and the limits of the conclusions it supports. Last reviewed: **13 November 2026**. ## Penetration-test report availability No independent penetration-test report or independent penetration-test executive summary is currently published through this assurance documentation. The internal source review described below is available as supporting evidence, but is not a substitute for such a report. A proposed test, access to a testing tool, a dependency scan or the existence of CI security jobs does not establish that a penetration test has been completed. Customers requiring independent assessment evidence should record it as unavailable from the current public evidence set rather than treating the internal review as an external test. ## Published internal security review The [ServiceStack v10.2 release materials](https://docs.servicestack.net/releases/v10_02) document an internal AI-assisted security and reliability review. Public reports describe findings and source changes across packages, including input handling, serialization, path boundaries, SQL construction and resource management. | Area | Public source report | | --- | --- | | ServiceStack.Common | [Common security changes](https://github.com/ServiceStack/ServiceStack/blob/main/ServiceStack/src/ServiceStack.Common/SECURITY_CHANGES.md) | | ServiceStack.Interfaces | [Interfaces security changes](https://github.com/ServiceStack/ServiceStack/blob/main/ServiceStack/src/ServiceStack.Interfaces/SECURITY_CHANGES.md) | | ServiceStack.Text | [Text security changes](https://github.com/ServiceStack/ServiceStack/blob/main/ServiceStack.Text/SECURITY_CHANGES.md) | | ServiceStack.OrmLite and database dialects | [OrmLite security changes](https://github.com/ServiceStack/ServiceStack/blob/main/ServiceStack.OrmLite/SECURITY_CHANGES.md) | | Broader review scope | [v10.2 audit and hardening overview](https://docs.servicestack.net/releases/v10_02) | These are living source reports. A source change is not by itself proof that a particular deployed release contains the fix. For version-specific review, identify the package version and source commit, and preserve a commit-pinned copy of the relevant report and verification evidence. ## Assessment dates, scope and remediation status The internal source-review overview was published with **v10.2 on 13 August 2026**. This is the release documentation date, not a claimed start/end date for a penetration test. The linked security-change reports continue to evolve; use commit-pinned reports for a historical assessment. Current automated dependency observations carry their own scan dates and package scopes. No dated external penetration-test report is available in this public evidence set. An assessment of a deployed example application would cover that application's tested configuration and package versions, rather than every library API, consumer configuration or company system. A publishable assessment executive summary needs to identify: - the assessment dates, assessor and methodology, including automated, AI-assisted or human-led testing; - the tested application, source revision, package versions and environment; - authenticated roles, tenant boundaries, included attack surfaces and exclusions; - findings by severity, affected versions and remediation or mitigation status; - verification or retest dates and any unresolved high/critical findings or residual risks. This describes the evidence needed for a future summary; it is not a report of a completed test. Any high/critical-risk mitigation statement must be tied to actual findings, fixes and verification in that scope. Sensitive reproduction details can be omitted from a public summary without hiding unresolved risk. ## How to interpret the evidence | Evidence | What it supports | What it does not establish | | --- | --- | --- | | Internal AI-assisted source review | Recorded source findings and remediation work in the documented scope | Independent penetration testing or exhaustive vulnerability coverage | | Automated tests and CI results | Behavior checked by the identified tests at a particular revision | Security of all untested paths or configurations | | SBOM and managed dependency observations | Package identity, dependency inventory and advisory matches in the stated data source | Runtime exploitation assessment, first-party code coverage or complete native-engine coverage | | Reviewed VEX, when published | A documented impact assessment for identified vulnerabilities and product variants | A general security certification or blanket all-clear | No blanket statement that all high or critical risks are mitigated is made by these pages. Such a conclusion requires an identified assessment scope, findings, remediation status and verification against the relevant release. ## Certifications and confidential material ServiceStack has not obtained independent organizational security or privacy certifications such as ISO 27001 or SOC 2. No independent organizational security-controls audit report is available in this public evidence set. The published product evidence should not be represented as either. See the [supplier assurance directory](/security/supplier-assurance) for the full evidence mapping. The public review reports, release evidence and security policy are the standard self-service assurance materials. Raw investigation records, sensitive exploitation details and internal infrastructure information are not included in public security bundles. ## Vulnerability disclosure Use the [ServiceStack security policy](https://servicestack.net/security) for private reporting and coordinated disclosure. Published assessments are historical evidence and do not replace monitoring current advisories and the actual dependencies resolved by your application. # EU Cyber Resilience Act and CE Marking Source: https://docs.servicestack.net/security/cra [Security Assurance](/security/) · [SBOM and VEX Downloads](/security/sbom-vex) · [Security Assessments](/security/assessments) This page states ServiceStack's current CRA readiness and CE-marking position for supplier assessments. Last reviewed: **12 November 2026**. ## CE-marking position ServiceStack's planned approach is to apply CE marking to products where legally required under the EU Cyber Resilience Act, after completing the applicable conformity assessment and EU Declaration of Conformity, by the relevant statutory application date. **ServiceStack is not currently asserting CRA conformity or CRA CE marking for the packages covered by this assurance documentation.** Product applicability, classification, assessment route and security-support commitments remain under assessment. No signed CRA EU Declaration of Conformity is published here. This position is a readiness statement, not a certificate or declaration of conformity. It does not promise CE marking for components outside the regulation's scope or certify a customer's integrated application. ## What must be completed The CRA places obligations on the product and its lifecycle. Depending on applicability, preparation includes: - defining the product boundary, intended use and applicable category; - recording cybersecurity risks and implementing applicable security requirements; - operating vulnerability intake, assessment, remediation, disclosure and reporting processes; - defining security-support coverage and providing the required user information; - assembling technical documentation and completing the applicable conformity assessment; - issuing the EU Declaration of Conformity and presenting the CE mark when conformity has been demonstrated. The [European Commission's manufacturer guidance](https://digital-strategy.ec.europa.eu/en/policies/cra-manufacturers) explains these stages. The [conformity-assessment guidance](https://digital-strategy.ec.europa.eu/en/policies/cra-conformity-assessment) explains why most products can use manufacturer self-assessment while certain important or critical categories require stricter procedures. This page does not assume every ServiceStack package has the same classification. ## Software components and presentation Separately marketed software components can fall within scope. Being a library or being embedded in another supplier's product is not, by itself, an exemption. Free and open-source software has specific scope provisions; public source availability alone does not settle applicability. Under Article 30 of the CRA, software CE marking can be presented on the EU Declaration of Conformity or the website accompanying the software. A logo inside each DLL or NuGet package is not the required presentation mechanism. Any future declaration and mark must clearly identify the product it covers. See the [CRA legal text, including Articles 2–3, 28–32 and Annexes I–II](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32024R2847) for the governing requirements. ## Application dates The CRA's main requirements generally apply from **11 December 2027**. Article 14 reporting obligations apply from **11 September 2026**. Transitional provisions affect products placed on the market earlier and products subsequently subject to substantial modification. These dates are distinct: a future conformity date does not defer an already applicable reporting obligation. See the [Commission CRA overview](https://digital-strategy.ec.europa.eu/en/policies/cyber-resilience-act) and Articles 69 and 71 of the regulation. ## Available readiness evidence For organization-level policy, certification status and separate NIS2/AI Act applicability statements, see [supplier security assurance](/security/supplier-assurance). | Area | Public evidence or current status | | --- | --- | | Package inventories and provenance | [Version-specific security bundles](/security/sbom-vex) | | Vulnerability-impact statements | [Reviewed VEX where available; absence explained](/security/sbom-vex#vex-information) | | Product review and assessment evidence | [Published security review and report availability](/security/assessments) | | Coordinated disclosure and private reporting | [ServiceStack security policy](https://servicestack.net/security) | | CRA declaration and CE marking | Not currently asserted or published for the covered packages | | Formal product security-support periods | Still under assessment; no new LTS or backport commitment is established by these pages | These materials support supplier due diligence. They do not, on their own, demonstrate completion of all CRA obligations. Customers integrating ServiceStack remain responsible for assessing their own product, resolved dependencies, deployment and applicable manufacturer obligations. # Create your first WebService Source: https://docs.servicestack.net/create-your-first-webservice
ServiceStack APIs start from a different place than most frameworks. Instead of writing a method that returns JSON, you describe **what the message is** - and the routes, the docs, the validation, the API Explorer and the native clients are all generated from that one description. This walkthrough creates a working API from scratch, then shows exactly what each file does and what you got for free.
That's it - you now have a running .NET 10 API. The template's home page is already calling it with typed DTOs! ## How it works
The important detail is what *isn't* in your Service: no `HttpContext`, no serialization, no routing code, no manual model binding. Your Service accepts a message and returns a message, which is what lets ServiceStack expose it over HTTP, MQs, gRPC or in-process without you changing a line. ## The code
## What that one DTO gave you
::: tip Change the return format on any API by adding `?format=json`, `?format=csv` or `?format=jsonl` - or by sending the matching `Accept` header. See [Formats](/formats) for the full list. ::: ## The solution structure Every ServiceStack template scaffolds the same four projects. The layout isn't ceremony - it's what makes your API contract shareable and your logic testable:
Read more in [Physical Project Structure](/physical-project-structure). ## Call your API from anywhere Your App publishes enough metadata to generate a native, typed client for any supported language - so there's no SDK project to write, version or document. Pick a language to see the two commands:
Re-run the generate command whenever your API changes. New fields show up in the generated DTOs, and removed or renamed members become **compile errors in the consuming App** instead of runtime surprises. ### From a web page, with no build step The `web` template's home page uses your App's built-in [JavaScript DTOs](/javascript-add-servicestack-reference) from [/types/mjs](/javascript-add-servicestack-reference) with the [@servicestack/client](/javascript-client) library, loaded from an [importmap](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap): ```html ``` Which lets you reference the package name in your source instead of its physical location: ```html
``` #### Enable static analysis and intelli-sense For IDE intelli-sense during development, save the annotated Typed DTOs to disk: :::sh npm run dtos ::: Then reference the local file to enable static analysis when calling your typed APIs: ```js import { Hello } from '/js/dtos.mjs' client.api(new Hello({ name })) ``` To also get type-checking for **@servicestack/client**, install the dependency-free library as a dev dependency: :::sh npm install -D @servicestack/client ::: Only its TypeScript definitions are used by the IDE, so you get a rich typed authoring experience with no bundler and no additional build time: ![](/img/pages/release-notes/v6.6/mjs-intellisense.png) ### From a component framework The same `JsonServiceClient` works in every JavaScript App, from SPAs to React Native to Node.js servers, e.g. with TypeScript & [Vue Single-File Components](https://vuejs.org/guide/scaling-up/sfc.html): ```html ``` Compare the same API call across the major front-end frameworks: - [Vue 3 HelloApi.mjs](https://github.com/NetCoreTemplates/blazor-vue/blob/main/MyApp/wwwroot/posts/components/HelloApi.mjs) - [Vue HelloApi.vue](https://github.com/NetCoreTemplates/vue-spa/blob/main/MyApp.Client/src/_posts/components/HelloApi.vue) - [Next.js with swrClient](https://github.com/NetCoreTemplates/nextjs/blob/main/ui/components/intro.tsx) - [React HelloApi.tsx](https://github.com/NetCoreTemplates/react-spa/blob/master/MyApp/src/components/Home/HelloApi.tsx) - [Angular HelloApi.ts](https://github.com/NetCoreTemplates/angular-spa/blob/master/MyApp/src/app/home/HelloApi.ts) Native Mobile and Desktop Apps use the same approach - see [Add ServiceStack Reference](/add-servicestack-reference) for Swift, Java, Kotlin, Dart and .NET clients. ## Where to go next
## Start from a full-featured template The `web` template is deliberately empty. When you want a template that comes with an opinionated front-end, auth, a database and deployment already wired up, start from one of the full project templates instead: ### [C# Project Templates Overview](/templates/)
For Blazor WASM and Server see our [Blazor projects & Tailwind components](/templates/blazor-tailwind), and the rich [Vue 3 Tailwind Components](/vue/) library that all Vue templates are pre-configured with. ## Other ways to create a project ::include empty-projects.md:: # Your first Web Service Explained Source: https://docs.servicestack.net/your-first-webservice-explained Let's look a bit deeper into the [Hello World service](/create-your-first-webservice#how-does-it-work) you created: As you have seen, the convention for response DTO is `RequestDTO` and `RequestDTOResponse`. **Note, request and response DTO should be in the same namespace if you want ServiceStack to recognize the DTO pair**. To support automatic exception handling, you also need to add a `ResponseStatus` property to the response DTO: ```csharp // Request DTO public class Hello : IReturn { public string Name { get; set; } } // Response DTO (follows naming convention) public class HelloResponse { public string Result { get; set; } public ResponseStatus ResponseStatus { get; set; } //Automatic exception handling } ``` Services are implemented in a class that either inherits from the `Service` base class or implements the `IService` empty marker interface. Inheriting from the convenient `Service` base class provides easy access to the most common functionality. ```csharp public class HelloService : Service { public object Any(Hello request) { return new HelloResponse { Result = $"Hello, {request.Name}" }; } } ``` The above service can be called with **Any** HTTP Verb (e.g. GET, POST,..) from any endpoint or format (e.g. JSON, XML, etc). You can also choose to handle a specific Verb by changing the method name to suit. E.g. you can limit the Service to only handle HTTP **GET** requests by using the `Get` method: ```csharp public class HelloService : Service { public object Get(Hello request) => new HelloResponse { Result = $"Hello, {request.Name}" }; } ``` ## Calling Web Services Thanks to the above `IReturn` interface marker you'll be able to use the terse, typed Service Client APIs, e.g: ```csharp var client = new JsonApiClient(BaseUri); HelloResponse response = client.Get(new Hello { Name = "World" }); ``` Request DTOs that don't implement `IReturn` will need to explicitly specify the Response DTO on their call-site, e.g: ```csharp HelloResponse response = client.Get(new Hello { Name = "World" }); HelloResponse response = client.Get("/hello/World!"); ``` Alternatively you could use a general purpose HTTP Client like [HTTP Utils](/http-utils): ```csharp HelloResponse response = "http://base.url/hello/World" .GetJsonFromUrl() .FromJson(); ``` We highly recommend annotating Request DTO's with the above `IReturn` marker as it enables a generic typed API without clients having to know and specify the Response at each call-site, which would be invalidated and need to be manually updated if the Service Response Type changes. More details on the Service Clients is available on the [C#/.NET Service Clients page](/csharp-client). ### Registering Custom Routes If no routes are defined the .NET Service Clients will use the [pre-defined Routes](/routing#pre-defined-routes). You can annotate your Request DTO with the `[Route]` attribute to register additional Custom Routes, e.g: ```csharp //Request DTO [Route("/hello")] [Route("/hello/{Name}")] public class Hello : IReturn { public string Name { get; set; } } ``` The .NET ServiceClients will then use the best matching Route based on the populated properties on the Request DTO. ### Routing Tips No **?queryString** or POST Form Data should be included in the route as ServiceStack automatically populates Request DTOs with all matching params, e.g: ```csharp [Route("/hello")] ``` Matches both `/hello` and `/hello?name=World` with the latter populating the `Name` Request DTO **public property**. When the route includes a variable, e.g: ```csharp [Route("/hello/{Name}")] ``` It only matches: ``` /hello/name ``` Whereas using a wildcard: ```csharp [Route("/hello/{Name*}")] ``` Matches all routes: ``` /hello /hello/name /hello/my/name/is/ServiceStack ``` More details about Routing is available on the [Routing page](/routing). # ServiceStack API design Source: https://docs.servicestack.net/api-design The primary difference between developing RPC vs ServiceStack's [Message-based Services](/what-is-a-message-based-web-service) is that the Services entire contract is defined by its typed messages, specifically the Request DTO which defines both the System inputs and identifies the System output. Typically both are POCO DTOs however the [response can be any serializable object](/service-return-types). The simplest Service example that does this is: ```csharp public class MyRequest : IReturn {} public class MyServices : Service { public object Any(MyRequest request) => request; } ``` As only the `Any()` wildcard method is defined, it will get executed whenever the `MyRequest` Service is invoked via **any HTTP Verb**, [gRPC](/grpc/), [MQ](/messaging) or [SOAP](/soap-support) Request. The Request DTO is also all that's required to invoke it via any [Typed Generic Service Client](/clients-overview) in any supported language, e.g: ```csharp MyRequest response = client.Get(new MyRequest()); ``` All Services are accessible by their [pre-defined routes](/routing#pre-defined-routes), we can turn it into a functional data-driven Service by annotating it with a [user-defined route](/routing) and changing the implementation to return all App Contacts: ```csharp public class Contact { public int Id { get; set; } public string Name { get; set; } } [Route("/contacts")] public class GetContacts : IReturn> { } public class ContactsService : Service { public object Get(GetContacts request) => Db.Select(); } ``` Which your C# clients will still be able to call with: ```csharp List response = client.Get(new GetContacts()); ``` This will make a **GET** call to the custom `/contacts` URL and returns all rows from the `Contact` Table in the configured RDBMS using [OrmLite](/ormlite/) `Select()` extension method on the `base.Db` ADO.NET `IDbConnection` property on ServiceStack's convenience `Service` base class. Using `Get()` limits access to this service from HTTP **GET** requests only, all other HTTP Verbs requests to `/contacts` will return a **404 NotFound** HTTP Error Response. ### Using explicit Response DTO Our recommendation instead of returning naked collections is returning an explicit predictable Response DTO, e.g: ```csharp [Route("/contacts")] public class GetContacts : IReturn { } public class GetContactsResponse { public List Results { get; set; } public ResponseStatus ResponseStatus { get; set; } } public class ContactsService : Service { public object Get(GetContacts request) => new GetContactsResponse { Results = Db.Select() }; } ``` Whilst slightly more verbose this style benefits from [more resilience in evolving and versioning](https://stackoverflow.com/a/12413091/85785) message-based Services and more coarse-grained APIs as additional results can be added to the Response DTO without breaking existing clients. You'll also need to follow the above convention if you also wanted to [support SOAP endpoints](/soap-support) or if you want to be able to handle Typed [Response Messages in MQ Services](/messaging#message-workflow). ### All APIs have a preferred default method Like the `Send*` APIs before them, both [API Explorer](/api-explorer) and the new [`Api*` methods](/csharp-client.html#high-level-api-and-apiasync-methods) send API requests using an APIs **preferred HTTP Method** which can be defined either: - Explicitly annotating Request DTOs with `IGet`, `IPost`, etc. **IVerb** interface markers - Using the verb specified in its user-defined `[Route]` attribute (if single verb specified) - Implicitly when using AutoQuery/CRUD Request DTOs - Using the Services **Verb()** implementation method if not using **Any()** If the HTTP Method can't be inferred, it defaults to using HTTP **POST**. But as good API documentation practice, we recommend specifying the HTTP Method each API should use, preferably using the `IVerb` interface marker, so it's embedded into the APIs Services Contract shared with clients (not required for AutoQuery APIs). ## ServiceStack's API Design We'll walk through a few examples here but for a more detailed look into the usages and capabilities of ServiceStack's API design checkout its [Comprehensive Test Suite](https://github.com/ServiceStack/ServiceStack/blob/master/tests/RazorRockstars.Console.Files/ReqStarsService.cs) At a minimum ServiceStack Services only need to implement the `IService` empty interface: ```csharp public interface IService {} ``` The interface is used as a Marker interface that ServiceStack uses to find, register and auto-wire your existing services. Although you're more likely going to want to inherit from ServiceStack's convenience concrete `Service` class which contains easy access to ServiceStack's providers: ```csharp public class Service : IService { IRequest Request { get; } // HTTP Request Context IResponse Response { get; } // HTTP Response Context IServiceGateway Gateway { get; } // Built-in Service Gateway IMessageProducer MessageProducer { get; } // Message Producer for Registered MQ Server void PublishMessage(T message); // Publish messages to Registered MQ Server IVirtualPathProvider VirtualFileSources { get; } // Virtual FileSystem Sources IVirtualFiles VirtualFiles { get; } // Writable Virtual FileSystem ICacheClient Cache { get; } // Registered Caching Provider ICacheClientAsync CacheAsync { get; } // Registered Async Caching Provider (or sync wrapper) MemoryCacheClient LocalCache { get; } // Local InMemory Caching Provider IDbConnection Db { get; } // Registered ADO.NET IDbConnection IRedisClient Redis { get; } // Registered RedisClient ValueTask GetRedisAsync(); // Registered Async RedisClient IAuthRepository AuthRepository { get; } // Registered User Repository IAuthRepositoryAsync AuthRepositoryAsync { get; } // Registered Async User Repository ISession SessionBag { get; } // Dynamic Session Bag ISessionAsync SessionBagAsync { get; } // Dynamic Async Session Bag Task SessionAsAsync(); // Resolve Typed UserSession Async TUserSession SessionAs(); // Resolve Typed UserSession IAuthSession GetSession() { get; } // Resolve base IAuthSession Task GetSessionAsync(); // Resolve base IAuthSession Async bool IsAuthenticated { get; } // Is Authenticated Request T TryResolve(); // Resolve dependency at runtime T ResolveService(); // Resolve an auto-wired service T GetPlugin(); // Resolve optional registered Plugin T AssertPlugin(); // Resolve required registered Plugin void Dispose(); // Override to implement custom IDispose ValueTask DisposeAsync(); // implement IAsyncDisposable (.NET v4.7.2+) } ``` ### Basic example - Handling Any HTTP Verb Lets revisit the Simple example from earlier: ```csharp [Route("/contacts")] public class GetContacts : IReturn> { } public class ContactsService : Service { public object Get(GetContacts request) => Db.Select(); } ``` ServiceStack maps HTTP Requests to your Services **Actions**. An Action is any method that: - Is `public` - Only contains a **single argument - the typed Request DTO** - Has a Method name matching a **HTTP Method** or **Any** (the fallback that can handle "ANY" method) - Methods can have **Format** suffix to handle specific formats, e.g. if exists `GetJson` will handle **GET JSON** requests - Can specify either `T` or `object` Return type, both have same behavior ### Content-Type Specific Service Implementations Service methods can also use `Verb{Format}` method names to provide a different implementation for handling a specific Content-Type. The Service below defines several different implementation for handling the same Request: ```csharp [Route("/my-request")] public class MyRequest { public string Name { get; set; } } public class ContentTypeServices : Service { public object GetJson(MyRequest request) => ..; // Handles GET /my-request for JSON responses public object GetHtml(MyRequest request) => // Handles GET /my-request for HTML Responses $@"

GetHtml {request.Name}

"; public object AnyHtml(MyRequest request) => // Handles other POST/PUT/etc Verbs for HTML Responses $@"

AnyHtml {request.Name}

"; public object Any(MyRequest request) => ...; // Handles all other unspecified Verbs/Formats } ``` ### Optional *Async Suffixes In addition your Services can optionally have the `*Async` suffix which by .NET Standard (and ServiceStack) guidelines is preferred for Async methods to telegraph to client call sites that its response should be awaited. ```csharp [Route("/contacts")] public class GetContacts : IReturn> { } public class ContactsService : Service { public async Task GetAsync(GetContacts request) => await Db.SelectAsync(); public object GetHtmlAsync(MyRequest request) => $@"

GetHtml {request.Name}

"; } ``` If both exists (e.g. `Post()` and `PostAsync()`) the `*Async` method will take precedence and be invoked instead. Allowing both is useful if you have internal services directly invoking other Services using `HostContext.ResolveService()` where you can upgrade your Service to use an Async implementation without breaking existing clients, e.g. this is used in [RegisterService.cs](https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack/Auth/RegisterService.cs): ```csharp [Obsolete("Use PostAsync")] public object Post(Register request) { try { var task = PostAsync(request); return task.GetResult(); } catch (Exception e) { throw e.UnwrapIfSingleException(); } } /// /// Create new Registration /// public async Task PostAsync(Register request) { //... async impl } ``` To change to use an async implementation whilst retaining backwards compatibility with existing call sites, e.g: ```csharp using var service = HostContext.ResolveService(Request); var response = service.Post(new Register { ... }); ``` This is important if the response is ignored as the C# compiler wont give you any hints to await the response which can lead to timing issues where the Services is invoked but User Registration hasn't completed as-is often assumed. Alternatively you can rename your method to use `*Async` suffix so the C# compiler will fail on call sites so you can replace the call-sites to `await` the async `Task` response, e.g: ```csharp using var service = HostContext.ResolveService(Request); var response = await service.PostAsync(new Register { ... }); ``` ### Group Services by Tag Related Services by can be grouped by annotating **Request DTOs** with the `[Tag]` attribute where they'll enable functionality in a number of ServiceStack's metadata services where they'll be used to [Group Services in Open API](https://swagger.io/docs/specification/grouping-operations-with-tags/). This feature could be used to tag which Services are used by different platforms: ```csharp [Tag("web")] public class WebApi : IReturn {} [Tag("mobile")] public class MobileApi : IReturn {} [Tag("web"),Tag("mobile")] public class WebAndMobileApi : IReturn {} ``` Where they'll appear as a tab to additionally filter APIs in metadata pages: ![](/img/pages/metadata/tag-groups.webp) They're also supported in [Add ServiceStack Reference](/add-servicestack-reference) where it can be used in the [IncludeTypes](/csharp-add-servicestack-reference#includetypes) DTO customization option where tags can be specified using braces in the format `{tag}` or `{tag1,tag2,tag3}`, e.g: ``` /* Options: IncludeTypes: {web,mobile} ``` Or individually: ``` /* Options: IncludeTypes: {web},{mobile} ``` It works similar to [Dependent Type References wildcard syntax](/csharp-add-servicestack-reference#include-request-dto-and-its-dependent-types) where it expands all Request DTOs with the tag to include all its reference types so including a `{web}` tag would be equivalent to including all Request DTOs & reference types with that reference, e.g: ``` /* Options: IncludeTypes: WebApi.*,WebAndMobileApi.* ``` ### Micro ORMs and ADO.NET's IDbConnection Code-First Micro ORMS like [OrmLite](/ormlite/) and [Dapper](https://github.com/StackExchange/Dapper) provides a pleasant high-level experience whilst working directly against ADO.NET's low-level `IDbConnection`. They both support all major databases so you immediately have access to a flexible RDBMS option out-of-the-box. At the same time you're not limited to using the providers contained in the `Service` class and can continue to use your own register IOC dependencies (inc. an alternate IOC itself). ### Micro ORM POCOs make good DTOs The POCOs used in Micro ORMS are particularly well suited for re-using as DTOs since they don't contain any circular references that the Heavy ORMs have (e.g. EF). OrmLite goes 1-step further and borrows pages from NoSQL's playbook where any complex property e.g. `List` is transparently blobbed in a schema-less text field, promoting the design of frictionless **Pure POCOS** that are uninhibited by RDBMS concerns. In many cases these POCO data models already make good DTOs and can be returned directly instead of mapping to domain-specific DTOs. ### Calling Services from a Typed C# Client In Service development your services DTOs provides your technology agnostic **Service Layer** which you want to keep clean and as 'dependency-free' for maximum accessibility and potential re-use. Our recommendation is to follow our [Recommended Physical Project Structure](/physical-project-structure) and keep your DTOs in a separate ServiceModel project which ensures a well-defined ServiceContract [decoupled from their implementation and accessible from any client](/service-complexity-and-dto-roles#data-transfer-objects---dtos). This recommended Physical project structure is embedded in each [ServiceStack VS.NET Template](/templates/). One of ServiceStack's strengths is its ability to re-use your Server DTOs on the client enabling ServiceStack's productive end-to-end typed API. ServiceStack's use of Typed DTOs in its message-based design enable greater resiliency for your Services where the exact DTOs aren't needed, only the shape of the DTOs is important and clients can also opt to use partial DTOs containing just the fields they're interested in. In the same way extending existing Services with new optional properties wont break existing clients using older DTOs. When developing both Server and Client applications the easiest way to call typed Services from clients is to just have them reference the same ServiceModel .dll the Server uses to define its Service Contract, or for clients that only need to call a couple of Service you can choose to instead copy the class definitions as-is, in both cases calling Services is exactly the same where the Request DTO can be used with any of the generic [C#/.NET Service Clients](/csharp-client) to call Services using a succinct typed API, e.g: #### Service Model Classes ```csharp [Route("/contacts")] public class GetContacts : IReturn> { } public class Contact { ... } ``` Which can used in any ServiceClient with: ```csharp var client = new JsonApiClient(BaseUri); List response = client.Get(new GetContacts()); ``` Which makes a **GET** web request to the `/contacts` route. Custom Routes on Request DTO's are also not required as when none are defined the client automatically falls back to using ServiceStack's [pre-defined routes](/routing#pre-defined-routes). ### Generating Typed DTOs In addition to being able to share your `ServiceModel.dll` on .NET Clients enable a typed end-to-end API without code-gen, clients can alternatively choose to use [Add ServiceStack Reference](/csharp-add-servicestack-reference) support to provide an alternative way to get the Services typed DTOs on the client. In both cases the exact same source code is used to call the Services: ```csharp var client = new JsonApiClient(BaseUri); var response = client.Get(new GetContacts()); ``` Add ServiceStack Reference is also available for [most popular languages](/add-servicestack-reference) used in developing Web, Mobile and Desktop Apps. #### Custom API Requests When preferred, you can also use the previous more explicit client API (ideal for when you don't have the `IReturn<>` marker) which lets you call the Service using just its route: ```csharp var response = client.Get>("/contacts"); ``` ::: info All these Service Client APIs **have async equivalents** with an `*Async` suffix ::: ### API QueryParams ServiceStack's message-based design is centered around sending a single message which is all that's required to invoke any Typed API, however there may be times when you need to send additional params where you can't change the API's Request DTO definition or in AutoQuery's case its [Implicit Conventions](/autoquery/rdbms#implicit-conventions) would require too many permutations to be able to type the entire surface area on each Request DTO. Typically this would inhibit being able to invoke these Services from a typed Service Client API that would instead need to either use the untyped [`Get(relativeUrl)`](https://reference.servicestack.net/api/ServiceStack/IRestClient/#-gettresponsestring) ServiceClient APIs or [HTTP Utils](/http-utils) to construct the API Request path manually. Alternatively Request DTOs can implement `IHasQueryParams` where any entries will be sent as additional query params along with the typed DTO: ```csharp public interface IHasQueryParams { Dictionary QueryParams { get; set; } } ``` Which is available in all AutoQuery DTOs where it's added as a non-serializable property so it's only included in the QueryString: ```csharp [DataContract] public abstract class QueryBase : IQuery, IHasQueryParams { //... [IgnoreDataMember] public virtual Dictionary QueryParams { get; set; } } ``` Which allows using existing ServiceClient typed APIs to send a combination of untyped queries in AutoQuery requests, e.g: ```csharp var api = await client.ApiAsync(new QueryContacts { IdsIn = new[]{ 1, 2, 3 }, QueryParams = new() { ["LastNameStartsWith"] = "A" } }); ``` ## Everything centered around Request DTOs A nice property of ServiceStack's message-based design is all functionality is centered around Typed Request DTOs which easily lets you take advantage of high-level value-added functionality like [Auto Batched Requests](/auto-batched-requests) or [Encrypted Messaging](/auth/encrypted-messaging) which are enabled automatically without any effort or easily opt-in to enhanced functionality by decorating Request DTOs or thier Services with Metadata and [Filter Attributes](/filter-attributes) and everything works together, binded against typed models naturally. E.g. you can take advantage of [ServiceStack's Razor support](https://razor.netcore.io/) and create a web page for this service by just adding a Razor view with the same name as the Request DTO in the `/Views` folder, which for the `GetContacts` Request DTO you can just add `/Views/GetContacts.cshtml` and it will get rendered with the Services Response DTO as its View Model when the Service is called from a browser (i.e. HTTP Request with `Accept: text/html`). Thanks to ServiceStack's built-in Content Negotiation you can fetch the HTML contents calling the same url: ```csharp var html = $"{BaseUri}/contacts".GetStringFromUrl(accept:"text/html"); ``` This [feature is particularly nice](https://razor.netcore.io/#unified-stack) as it lets you **re-use your existing services** to serve both Web and Native Mobile and Desktop clients. ### Action Filters Service actions can also contain fine-grained application of Request and Response filters, e.g: ```csharp public class ContactsService : Service { [ClientCanSwapTemplates] public object Get(GetContacts request) => Db.Select(); } ``` This Request Filter allows the client to [change the selected Razor **View** and **Template**](https://razor.netcore.io/#unified-stack) used at runtime. By default the view with the same name as the **Request** or **Response** DTO is used. ## Handling different HTTP Verbs ServiceStack Services lets you handle any HTTP Verb in the same way, e.g this lets you respond with CORS headers to a HTTP **OPTIONS** request with: ```csharp public class ContactsService : Service { [EnableCors] public void Options(GetContact request) {} } ``` Which if you now make an OPTIONS request to the above service, will emit the default `[EnableCors]` headers: ```csharp var webReq = (HttpWebRequest)WebRequest.Create(Host + "/contacts"); webReq.Method = "OPTIONS"; using var webRes = webReq.GetResponse(); webRes.Headers["Access-Control-Allow-Origin"] // * webRes.Headers["Access-Control-Allow-Methods"] // GET, POST, PUT, DELETE, OPTIONS webRes.Headers["Access-Control-Allow-Headers"] // Content-Type ``` ### PATCH request example Handling a PATCH request is just as easy, e.g. here's an example of using PATCH to handle a partial update of a Resource: ```csharp [Route("/contacts/{Id}", "PATCH")] public class UpdateContact : IReturn { public int Id { get; set; } public int Age { get; set; } } public Contact Patch(UpdateContact request) { var Contact = request.ConvertTo(); Db.UpdateNonDefaults(Contact); return Db.SingleById(request.Id); } ``` And the client call is just as easy as you would expect: ```csharp var response = client.Patch(new UpdateContact { Id = 1, Age = 18 }); ``` Although sending different HTTP Verbs are unrestricted in native clients, they're unfortunately not allowed in some web browsers and proxies. So to simulate a PATCH from an AJAX request you need to set the **X-Http-Method-Override** HTTP Header. ## Structured Error Handling When following the [explicit Response DTO Naming convention](/error-handling#error-response-types) ServiceStack will automatically populate the `ResponseStatus` property with a structured Error Response otherwise if returning other DTOs like naked collections ServiceStack will instead return a generic `ErrorResponse`, although this is mostly a transparent technical detail you don't need to know about as for schema-less formats like JSON they return the exact same wire-format. [Error Handling](/error-handling) works naturally in ServiceStack where you can simply throw C# Exceptions, e.g: ```csharp public List Post(Contact request) { if (!request.Age.HasValue) throw new ArgumentException("Age is required"); Db.Insert(request.ConvertTo()); return Db.Select(); } ``` This will result in an Error thrown on the client if it tried to create an empty Contact: ```csharp try { var response = client.Post(new Contact()); } catch (WebServiceException webEx) { webEx.StatusCode // 400 webEx.StatusDescription // ArgumentException webEx.ResponseStatus.ErrorCode // ArgumentException webEx.ResponseStatus.Message // Age is required webEx.ResponseDto is ErrorResponse // true } ``` The same Service Clients Exception handling is also used to handle any HTTP error generated in or outside of your service, e.g. here's how to detect if a HTTP Method isn't implemented or disallowed: ```csharp try { var response = client.Send(new SearchContacts()); } catch (WebServiceException webEx) { webEx.StatusCode // 405 webEx.StatusDescription // Method Not Allowed } ``` In addition to standard C# exceptions your services can also return multiple, rich and detailed validation errors as enforced by [Fluent Validation's validators](/validation). ### Overriding the default Exception handling You can override the default exception handling in ServiceStack by registering a `ServiceExceptionHandlers`, e.g: ```csharp void Configure(Container container) { this.ServiceExceptionHandlers.Add((req, reqDto, ex) => { return ...; }); } ``` ## Smart Routing For the most part you won't need to know about this as ServiceStack's routing works as you would expect. Although this should still serve as a good reference to describe the resolution order of ServiceStack's Routes: 1. Any exact Literal Matches are used first 2. Exact Verb match is preferred over All Verbs 3. The more variables in your route the less weighting it has 4. When Routes have the same weight, the order is determined by the position of the Action in the service or Order of Registration (FIFO) These Rules only come into play when there are multiple routes that matches the pathInfo of an incoming request. Lets see some examples of these rules in action using the routes defined in the [API Design test suite](https://github.com/ServiceStack/ServiceStack/blob/master/tests/RazorRockstars.Console.Files/ReqStarsService.cs): ```csharp [Route("/contacts")] public class Contact {} [Route("/contacts", "GET")] public class GetContacts {} [Route("/contacts/{Id}", "GET")] public class GetContact {} [Route("/contacts/{Id}/{Field}")] public class ViewContact {} [Route("/contacts/{Id}/delete")] public class DeleteContact {} [Route("/contacts/{Id}", "PATCH")] public class UpdateContact {} [Route("/contacts/reset")] public class ResetContact {} [Route("/contacts/search")] [Route("/contacts/aged/{Age}")] public class SearchContacts {} ``` These are results for these HTTP Requests ``` GET /contacts => GetContacts POST /contacts => Contact GET /contacts/search => SearchContacts GET /contacts/reset => ResetContact PATCH /contacts/reset => ResetContact PATCH /contacts/1 => UpdateContact GET /contacts/1 => GetContact GET /contacts/1/delete => DeleteContact GET /contacts/1/foo => ViewContact ``` And if there were multiple of the exact same routes declared like: ```csharp [Route("/req/{Id}", "GET")] public class Req2 {} [Route("/req/{Id}", "GET")] public class Req1 {} public class MyService : Service { public object Get(Req1 request) { ... } public object Get(Req2 request) { ... } } ``` The Route on the Action that was declared first gets selected, i.e: ``` GET /req/1 => Req1 ``` ### Populating Complex Type Properties on QueryString ServiceStack uses the [JSV-Format](/jsv-format) (JSON without quotes) to parse QueryStrings. JSV lets you embed deep object graphs in QueryString as seen [this example url](https://test.servicestack.net/json/reply/StoreLogs?Loggers=%5B%7BId:786,Devices:%5B%7BId:5955,Type:Panel,TimeStamp:1199303309,Channels:%5B%7BName:Temperature,Value:58%7D,%7BName:Status,Value:On%7D%5D%7D,%7BId:5956,Type:Tank,TimeStamp:1199303309,Channels:%5B%7BName:Volume,Value:10035%7D,%7BName:Status,Value:Full%7D%5D%7D%5D%7D%5D): ``` https://test.servicestack.net/json/reply/StoreLogs?Loggers=[{Id:786,Devices:[{Id:5955,Type:Panel, Channels:[{Name:Temperature,Value:58},{Name:Status,Value:On}]}, {Id:5956,Type:Tank,TimeStamp:1199303309, Channels:[{Name:Volume,Value:10035},{Name:Status,Value:Full}]}]}] ``` ## Advanced Usages ### Custom Hooks The ability to extend ServiceStack's service execution pipeline with Custom Hooks is an advanced customization feature that for most times is not needed as the preferred way to add composable functionality to your services is to use [Request / Response Filter attributes](/filter-attributes) or apply them globally with [Global Request/Response Filters](/request-and-response-filters). ### Custom Serialized Responses The new `IHttpResult.ResultScope` API provides an opportunity to execute serialization within a custom scope, e.g. this can be used to customize the serialized response of adhoc services that's different from the default global configuration with: ```csharp return new HttpResult(dto) { ResultScope = () => JsConfig.With(new Config { IncludeNullValues = true }) }; ``` Which enables custom serialization behavior by performing the serialization within the custom scope, equivalent to: ```csharp using (JsConfig.With(new Config { IncludeNullValues = true })) { var customSerializedResponse = Serialize(dto); } ``` ### Request and Response Converters The [Encrypted Messaging Feature](/auth/encrypted-messaging) takes advantage of Request and Response Converters that let you change the Request DTO and Response DTO's that get used in ServiceStack's Request Pipeline where: #### Request Converters Request Converters are executed directly after any [Custom Request Binders](/serialization-deserialization#create-a-custom-request-dto-binder): ```csharp appHost.RequestConverters.Add(async (req, requestDto) => { //Return alternative Request DTO or null to retain existing DTO }); ``` #### Response Converters Response Converters are executed directly after the Service: ```csharp appHost.ResponseConverters.Add(async (req, response) => //Return alternative Response or null to retain existing Service response }); ``` ### Intercept Service Requests As an alternative to creating a [Custom Service Runner](#using-a-custom-servicerunner) to intercept different events when processing ServiceStack Requests, you can instead override the `OnBeforeExecute()`, `OnAfterExecute()` and `OnExceptionAsync()` callbacks in your `Service` class (or base class) to intercept and modify Request DTOs, Responses or Error Responses, e.g: ```csharp class MyServices : Service { // Log all Request DTOs that implement IHasSessionId public override void OnBeforeExecute(object requestDto) { if (requestDto is IHasSessionId dtoSession) { Log.Debug($"{nameof(OnBeforeExecute)}: {dtoSession.SessionId}"); } } //Return Response DTO Name in HTTP Header with Response public override object OnAfterExecute(object response) { return new HttpResult(response) { Headers = { ["X-Response"] = response.GetType().Name } }; } //Return custom error with additional metadata public override Task OnExceptionAsync(object requestDto, Exception ex) { var error = DtoUtils.CreateErrorResponse(requestDto, ex); if (error is IHttpError httpError) { var errorStatus = httpError.Response.GetResponseStatus(); errorStatus.Meta = new Dictionary { ["InnerType"] = ex.InnerException?.GetType().Name }; } return Task.FromResult(error); } } ``` #### Async Callbacks For async callbacks your Services can implement `IServiceBeforeFilterAsync` and `IServiceAfterFilterAsync`, e.g: ```csharp public class MyServices : Service, IServiceBeforeFilterAsync, IServiceAfterFilterAsync { public async Task OnBeforeExecuteAsync(object requestDto) { //... } public async Task OnAfterExecuteAsync(object response) { //... return response; } } ``` If you're implementing `IService` instead of inheriting the concrete `Service` class, you can implement the interfaces directly: ```csharp // Handle all callbacks public class MyServices : IService, IServiceFilters { //.. } // Or individually, just the callbacks you want public class MyServices : IService, IServiceBeforeFilter, IServiceAfterFilter, IServiceErrorFilter { //.. } ``` ### Custom Service Runner The [IServiceRunner](https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Interfaces/Web/IServiceRunner.cs) decouples the execution of your service from the implementation of it which provides an alternative custom hook which lets you add custom behavior to all Services without needing to use a base Service class. To add your own Service Hooks you just need to override the default Service Runner in your AppHost from its default implementation: ```csharp public virtual IServiceRunner CreateServiceRunner(ActionContext actionContext) { return new ServiceRunner(this, actionContext); //Cached per Service Action } ``` With your own: ```csharp public override IServiceRunner CreateServiceRunner(ActionContext actionContext) { return new MyServiceRunner(this, actionContext); //Cached per Service Action } ``` Where `MyServiceRunner` is just a custom class implementing the custom hooks you're interested in, e.g: ```csharp public class MyServiceRunner : ServiceRunner { public override OnBeforeExecute(IRequest req, TRequest request, object service) { // Called just before any Action is executed } public override Task ExecuteAsync(IRequest req, object instance, TRequest requestDto) { // Called to execute the Service instance with the requestDto return base.ExecuteAsync(req, serviceInstance, requestDto); } public override object OnAfterExecute(IRequest req, object response, object service) { // Called just after any Action is executed, you can modify the response returned here as well } public override Task HandleExceptionAsync(IRequest req, TRequest requestDto, Exception ex, object instance) { // Called whenever an exception is thrown in your Services Action } } ``` ## Limitations One limitation of Services is that you can't split the handling of a single Resource (i.e. Request DTO) over multiple service implementations. If you find you need to do this because your service is getting too big, consider using partial classes to spread the implementation over multiple files. Another option is encapsulating some of the re-usable functionality into Logic dependencies and inject them into your service. ## Other Notes Although they're not needed or used anywhere [you can also use HTTP Verb interfaces](https://github.com/ServiceStack/ServiceStack/blob/34acc429ee04053ea766e4fb183e7aad7321ef5e/src/ServiceStack.Interfaces/IService.cs#L27) to enforce the correct signature required by the services, e.g: ```csharp public class MyService : Service, IAny, IGet, IPost { public object Any(GetContacts request) { .. } public object Get(SearchContacts request) { .. } public object Post(Contact request) { .. } } ``` This has no effect to the runtime behaviour and your services will work the same way with or without the added interfaces. # Service Return Types Source: https://docs.servicestack.net/service-return-types From a birds-eye view ServiceStack can return any of: - Any **DTO** object -> serialized to Response ContentType - `HttpResult`, `HttpError`, `CompressedResult` or other `IHttpResult` for Customized HTTP response #### Services should only return Reference Types If a Value Type like `int` or `long` response is needed, it's recommended to wrap the Value Type in a Response DTO, e.g: ```csharp public class MyResponse { public int Result { get; set; } } ``` Alternatively you can return a naked Value Type response by returning it as a `string`, e.g: ```csharp public object Any(MyRequest request) => "1"; ``` ## Different Return Types The following types are not converted (to different Content-Types) but get written directly to the Response Stream: - `String` - `Stream` - `IStreamWriter` - `byte[]` - with the `application/octet-stream` Content Type - `ReadOnlyMemory` - `ReadOnlyMemory` From the [HelloWorld ServiceStack.UseCase](https://github.com/ServiceStack/ServiceStack.UseCases/blob/master/HelloWorld/Global.asax.cs) demo: ```csharp public class HelloService : Service { public HelloResponse Get(Hello request) { return new HelloResponse { Result = $"Hello, {request.Name}!" }; //C# client can call with: //var response = client.Get(new Hello { Name = "ServiceStack" }); } public string Get(HelloHtml request) { return $"

Hello, {request.Name}!

"; } [AddHeader(ContentType = "text/plain")] public string Get(HelloText request) { return $"

Hello, {request.Name}!

"; } [AddHeader(ContentType = "image/png")] public Stream Get(HelloImage request) { var width = request.Width.GetValueOrDefault(640); var height = request.Height.GetValueOrDefault(360); var bgColor = request.Background != null ? Color.FromName(request.Background) : Color.ForestGreen; var fgColor = request.Foreground != null ? Color.FromName(request.Foreground) : Color.White; var image = new Bitmap(width, height); using (var g = Graphics.FromImage(image)) { g.Clear(bgColor); var drawString = $"Hello, {request.Name}!"; var drawFont = new Font("Times", request.FontSize.GetValueOrDefault(40)); var drawBrush = new SolidBrush(fgColor); var drawRect = new RectangleF(0, 0, width, height); var drawFormat = new StringFormat { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center }; g.DrawString(drawString, drawFont, drawBrush, drawRect, drawFormat); var ms = new MemoryStream(); image.Save(ms, ImageFormat.Png); return ms; } } } ``` #### Live Examples of the above Hello Service: - [/hello/ServiceStack](http://bootstrapapi.apphb.com/api/hello/ServiceStack) - [/hello/ServiceStack?format=json](http://bootstrapapi.apphb.com/api/hello/ServiceStack?format=json) - [/hellotext/ServiceStack](http://bootstrapapi.apphb.com/api/hellotext/ServiceStack) - [/hellohtml/ServiceStack](http://bootstrapapi.apphb.com/api/hellohtml/ServiceStack) - [/helloimage/ServiceStack?Width=600&height=300&Foreground=Yellow](http://bootstrapapi.apphb.com/api/helloimage/ServiceStack?Width=600&height=300&Foreground=Yellow) ### Content-Type Specific Service Implementations Service implementations can use `Verb{Format}` method names to provide a different implementation for handling a specific Content-Type, e.g. the Service below defines several different implementation for handling the same Request: ```csharp [Route("/my-request")] public class MyRequest { public string Name { get; set; } } public class ContentTypeServices : Service { // Handles all other unspecified Verbs/Formats to /my-request public object Any(MyRequest request) => ...; // Handles GET /my-request for JSON responses public object GetJson(MyRequest request) => ..; // Handles POST/PUT/DELETE/etc /my-request for HTML Responses public object AnyHtml(MyRequest request) => $@"

AnyHtml {request.Name}

"; // Handles GET /my-request for HTML Responses public object GetHtml(MyRequest request) => $@"

GetHtml {request.Name}

"; } ``` This convention can be used for any of the formats listed in `ContentTypes.KnownFormats`, which by default includes: - json - xml - jsv - csv - html - protobuf - msgpack - wire ## Partial Content Support Partial Content Support allows a resource to be split up an accessed in multiple chunks for clients that support HTTP Range Requests. This is a popular feature in download managers for resuming downloads of large files and streaming services for real-time streaming of content (e.g. consumed whilst it's being watched or listened to). [HTTP Partial Content Support](http://benramsey.com/blog/2008/05/206-partial-content-and-range-requests/) is added in true ServiceStack-style where it's now automatically and transparently enabled for any existing services returning: #### A Physical File ```csharp return new HttpResult(new FileInfo(filePath), request.MimeType); ``` #### A Virtual File ```csharp return new HttpResult(VirtualFileSources.GetFile(virtualPath)); ``` #### A Memory Stream ```csharp return new HttpResult(ms, "audio/mpeg"); ``` #### Raw Bytes ```csharp return new HttpResult(bytes, "image/png"); ``` #### Raw Text ```csharp return new HttpResult(customText, "text/plain"); ``` Partial Content was also added to static file downloads served directly through ServiceStack which lets you stream mp3 downloads or should you ever want to your static .html, .css, .js, etc. You can disable Partial Content support with `Config.AllowPartialResponses = false;`. See the [PartialContentResultTests](https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.WebHost.Endpoints.Tests/PartialContentResultTests.cs) for more examples. ## Writing directly to the Response Stream In addition to returning plain C# objects, ServiceStack allows you to return any **Stream** or `IStreamWriterAsync` (which is a bit more flexible on how you write to the response stream): ```csharp public interface IStreamWriterAsync { Task WriteToAsync(Stream responseStream, CancellationToken token=default); } ``` Both though allow you to write directly to the Response OutputStream without any additional conversion overhead. ### Customizing HTTP Headers If you want to customize the HTTP headers at the same time you just need to implement [IHasOptions](https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Interfaces/Web/IHasOptions.cs) where any Dictionary Entry is written to the Response HttpHeaders. ```csharp public interface IHasOptions { IDictionary Options { get; } } ``` Further than that, the IHttpResult allows even finer-grain control of the HTTP output (status code, headers, ...) where you can supply a custom Http Response status code. You can refer to the implementation of the [HttpResult](https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack/HttpResult.cs) object for a real-world implementation of these above interfaces. ### Further customizing the HTTP Response See the [Customize HTTP Responses](/customize-http-responses) page for more ways of customizing the HTTP Response. # Design RESTful Services Source: https://docs.servicestack.net/design-rest-services ServiceStack encourages a message-based design so each Service should have its own distinct message (aka Request DTO) where it's able to use explicit properties to define what each Service accepts. Something to keep in mind is how you define and design your Services in ServiceStack are de-coupled in how you expose them which can be exposed under any custom Route. ### Use a logical / hierarchical Url structure We recommend adopting a logical hierarchically structured URL that represents the identifier of a resource, i.e. the parent path categorizes your resource and gives it meaningful context. So if you needed to design an API for System that maintained **Events** and their **Reviews** it could adopt the following url structure: ``` /events # all events /events/1 # event #1 /events/1/reviews # event #1 reviews ``` Where each of the above resource identifiers can be invoked using any HTTP **Verb** which represents the action to take on them, e.g: ``` GET /events # View all Events POST /events # Create a new Event PUT /events/{Id} # Update an existing Event DELETE /events/{Id} # Delete an existing Event ``` ### Implementing RESTful Routes For their implementation ServiceStack encourages a message-based design that groups all related operations based on **Response type** and **Call Context**. For an Events and Reviews system it could look something like: ```csharp [Route("/events", "GET")] [Route("/events/category/{Category}", "GET")] // Optional GET example public class SearchEvents : IReturn> { //resultset filter examples, e.g. ?Category=Tech&Query=servicestack public string Category { get; set; } public string Query { get; set; } } [Route("/events", "POST")] public class CreateEvent : IReturn { public string Name { get; set; } public DateTime StartDate { get; set; } } [Route("/events/{Id}", "GET")] [Route("/events/code/{EventCode}", "GET")] // Alternative Id public class GetEvent : IReturn { public int Id { get; set; } public string EventCode { get; set; } // Alternative to fetch Events } [Route("/events/{Id}", "PUT")] public class UpdateEvent : IReturnVoid { public int Id { get; set; } public string Name { get; set; } public DateTime StartDate { get; set; } } ``` Event Reviews would follow a similar pattern: ```csharp [Route("/events/{EventId}/reviews", "GET")] public class GetEventReviews : IReturn> { public int EventId { get; set; } } [Route("/events/{EventId}/reviews/{Id}", "GET")] public class GetEventReview : IReturn { public int EventId { get; set; } public int Id { get; set; } } [Route("/events/{EventId}/reviews", "POST")] public class CreateEventReview : IReturn { public int EventId { get; set; } public string Comments { get; set; } } ``` The above REST Service examples returns naked Types and collections which [ServiceStack has a great story for](/api-design#structured-error-handling), however our personal preference is to design more coarse-grained and versionable [Message-based APIs](/design-message-based-apis) where we'd use an explicit Response DTO for each Service, e.g: ```csharp [Route("/events/{EventId}/reviews", "GET")] public class GetEventReviews : IReturn { public int EventId { get; set; } } public class GetEventReviewsResponse { public List Results { get; set; } } [Route("/events/{EventId}/reviews/{Id}", "GET")] public class GetEventReview : IReturn { public int EventId { get; set; } public int Id { get; set; } } public class GetEventReviewResponse { public EventReview Result { get; set; } public ResponseStatus ResponseStatus { get; set; } // inject structured errors if any } [Route("/events/{EventId}/reviews", "POST")] public class CreateEventReview : IReturn { public int EventId { get; set; } public string Comments { get; set; } } public class CreateEventReviewResponse { public EventReview Result { get; set; } public ResponseStatus ResponseStatus { get; set; } } ``` ### Notes The implementation of each Services then becomes straight-forward based on these messages, which (depending on code-base size) we'd recommend organizing in 2 **EventsService** and **EventReviewsService** classes. Although `UpdateEvent` and `CreateEvent` are seperate Services here, if the use-case permits they can instead be handled by a single idempotent `StoreEvent` Service. ## [Physical Project Structure](/physical-project-structure) Ideally the root-level **AppHost** project should be kept lightweight and implementation-free. Although for small projects or prototypes with only a few services it's ok for everything to be in a single project and to simply grow your architecture when and as needed. For medium-to-large projects we recommend the physical structure below which for the purposes of this example we'll assume our Application is called **Events**. The order of the projects also show its dependencies, e.g. the top-level `Events` project references **all** sub projects whilst the last `Events.ServiceModel` project references **none**: ``` /Events AppHost.cs // ServiceStack Web or Self Host Project /Events.ServiceInterface // Service implementations (akin to MVC Controllers) EventsService.cs EventsReviewsService.cs /Events.Logic // For large projects: extract C# logic, data models, etc IGoogleCalendarGateway // E.g of a external dependency this project could use /Events.ServiceModel // Service Request/Response DTOs and DTO types Events.cs // SearchEvents, CreateEvent, GetEvent DTOs EventReviews.cs // GetEventReviews, CreateEventReview Types/ Event.cs // Event type EventReview.cs // EventReview type ``` With the `Events.ServiceModel` DTO's kept in their own separate implementation and dependency-free dll, you're freely able to share this dll in any .NET client project as-is - which you can use with any of the generic [C# Service Clients](/csharp-server-events-client) to provide an end-to-end typed API without any code-gen. ## More Info - This recommended project structure is embedded in all [ServiceStackVS VS.NET Templates](/templates/). - The [Simple Customer REST Example](/why-servicestack#simple-customer-database-rest-services-example) is a small self-contained, real-world example of creating a simple REST Service utilizing an RDBMS. # Design Message-based APIs Source: https://docs.servicestack.net/design-message-based-apis To give you a flavor of the differences you should think about when designing message-based services in ServiceStack we'll look at some examples to contrast WCF/WebApi vs ServiceStack's approach: ## WCF vs ServiceStack API Design WCF encourages you to think of web services as normal C# method calls, e.g: ```csharp public interface IWcfCustomerService { Customer GetCustomerById(int id); List GetCustomerByIds(int[] id); Customer GetCustomerByUserName(string userName); List GetCustomerByUserNames(string[] userNames); Customer GetCustomerByEmail(string email); List GetCustomerByEmails(string[] emails); } ``` This is what the same Service contract would look like in ServiceStack: ```csharp public class Customers : IReturn> { public int[] Ids { get; set; } public string[] UserNames { get; set; } public string[] Emails { get; set; } } ``` The important concept to keep in mind is that the entire query (aka Request) is captured in the Request Message (i.e. Request DTO) and not in the server method signatures. The obvious immediate benefit of adopting a message-based design is that any combination of the above RPC calls can be fulfilled in 1 remote message, by a single service implementation which improves cacheability and simplifies maintenance and testing with the reduced API surface area. ## WebApi vs ServiceStack API Design Likewise WebApi promotes a similar C#-like RPC Api that WCF does: ```csharp public class ProductsController : ApiController { public IEnumerable GetAllProducts() { return products; } public Product GetProductById(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return product; } public Product GetProductByName(string categoryName) { var product = products.FirstOrDefault((p) => p.Name == categoryName); if (product == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return product; } public IEnumerable GetProductsByCategory(string category) { return products.Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)); } public IEnumerable GetProductsByPriceGreaterThan(decimal price) { return products.Where((p) => p.Price > price); } } ``` ### ServiceStack Message-Based API Design Whilst ServiceStack encourages you to retain a Message-based Design: ```csharp public class SearchProducts : IReturn> { public string Category { get; set; } public decimal? PriceGreaterThan { get; set; } } public class GetProduct : IReturn { public int? Id { get; set; } public string Name { get; set; } } public class ProductsService : Service { public object Get(SearchProducts request) { var ret = products.AsQueryable(); if (request.Category != null) ret = ret.Where(x => x.Category == request.Category); if (request.PriceGreaterThan.HasValue) ret = ret.Where(x => x.Price > request.PriceGreaterThan.Value); return ret.ToList(); } public Product Get(GetProduct request) { var product = request.Id.HasValue ? products.FirstOrDefault(x => x.Id == request.Id.Value) : products.FirstOrDefault(x => x.Name == request.Name); if (product == null) throw new HttpError(HttpStatusCode.NotFound, "Product does not exist"); return product; } } ``` Again capturing the essence of the Request in the Request DTO. The message-based design is also able to condense **5 separate RPC** WebAPI Services into **2 message-based** ServiceStack Services. ## Group by Call Semantics and Response Types It's grouped into 2 different services in this example based on **Call Semantics** and **Response Types**: Every property in each Request DTO has the same semantics that is for `SearchProducts` each property acts like a Filter (e.g. an AND) whilst in `GetProduct` it acts like a combinator (e.g. an OR). The Services also return `List` and `Product` return types which will require different handling in the call-sites of Typed APIs. In WCF / WebAPI (and other RPC services frameworks) whenever you have a client-specific requirement you would add a new Server signature on the controller that matches that request. In ServiceStack's message-based approach however you're instead encouraged to think about where this feature intuitively fits and whether you're able to enhance existing services. You should also be thinking about how you can support the client-specific requirement in a **generic way** so that the same service could benefit other future potential use-cases. ### Separate One and Many Services We can use the above context as a guide to design new Services. If we needed to design a Bookings System that needed an API to return **All Bookings** and a **Single Booking** we'd use a separate Services as they'd have different Response Types, e.g. `GetBooking` returns 1 booking whilst `GetBookings` returns many. ### Distinguish Service Operations vs Types There should be a clean split between your Operations (aka Request DTOs) which is unique per service and is used to capture the Services' request, and the DTO types they return. Request DTOs are usually actions so they're verbs, whilst DTO types are entities/data-containers so they're nouns. ### Returning naked collections ServiceStack can return naked collections that [don't require a ResponseStatus](/error-handling#error-response-types) property since if it doesn't exist the generic `ErrorResponse` DTO will be thrown and serialized on the client instead which frees you from having your Responses contain `ResponseStatus` property. ### Returning coarse-grained Response DTOs However since they offer better versionability that can later be extended to return more results without breaking existing clients we prefer specifying explicit Response DTOs for each Service, although this is entirely optional. So our preferred message-based would look similar to: ```csharp // Operations [Route("/bookings/{Id}")] public class GetBooking : IReturn { public int Id { get; set; } } public class GetBookingResponse { public Booking Result { get; set; } public ResponseStatus ResponseStatus { get; set; } // inject structured errors } [Route("/bookings/search")] public class SeachBookings : IReturn { public DateTime BookedAfter { get; set; } } public class SeachBookingsResponse { public List Results { get; set; } public ResponseStatus ResponseStatus { get; set; } // inject structured errors } // Types public class Booking { public int Id { get; set; } public int ShiftId { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public int Limit { get; set; } } ``` When they're not ambiguous we'll typiclly leave out specifying the **Verb** in `[Route]` definitions for **GET** Requests as its unnecessary. ### Using AutoQuery Where possible we'll also use [AutoQuery for Search Services](/autoquery/rdbms) which require dramatically less effort whilst offering a lot more functionality out-of-the-box. E.g. The Search Bookings Service with AutoQuery could adopt the same Customer Route and properties: ```csharp [Route("/bookings/search")] public class SeachBookings : QueryDb { public DateTime BookedAfter { get; set; } } ``` But no implementation is needed as AutoQuery automatically creates the optimal implementation. AutoQuery also supports [Implicit Conventions](/autoquery/rdbms#implicit-conventions) where you're able to filter by any of `Booking` table columns without any additional code or effort. ### Keep a consistent Nomenclature You should reserve the word **Get** on services which query on unique or Primary Keys fields, i.e. when a supplied value matches a field (e.g. Id) it only **Gets** 1 result. For "Search Services" that acts like a filter and returns multiple matching results which falls within a desired range we recommend using prefixing Services with the **Search** or **Find** verbs to signal the behavior of the Service. ### Self-describing Service Contracts Also try to be descriptive with each of your field names, these properties are part of your **public API** and should be self-describing as to what it does. E.g. By just looking at the Service Contract (e.g. Request DTO) we'd have no idea what a plain **Date** property means, as it could mean either **BookedAfter**, **BookedBefore** or **BookedOn** if it only returned bookings made on that Day. The benefit of this is now the call-sites of your [Typed .NET clients](/csharp-client) become easier to read: ```csharp Product product = client.Get(new GetProduct { Id = 1 }); var response = client.Get(new SearchBookings { BookedAfter = DateTime.Today }); ``` ## Service implementation [Filter Attributes](/filter-attributes) can be applied on either the **class** or **method** level, so when you need to secure all Operations within a given Service you can just annotate the top-level Service class with the `[Authenticate]`, e.g: ```csharp [Authenticate] public class BookingsService : Service { public object Get(GetBooking request) => ...; public object Get(SearchBookings request) => ...; } ``` ## Error Handling and Validation For info on how to add validation you either have the option to just [throw C# exceptions](/error-handling#throwing-c-exceptions) and apply your own customizations to them, in addition you also have the option to use the built-in [Declarative Validator](/declarative-validation) attributes on your Request DTO: ```csharp [ValidateIsAuthenticated] public class CreateBooking : IPost, IReturn { [ValidateNotNull] public DateTime? StartDate { get; set; } [ValidateGreatorThan(0)] public int ShiftId { get; set; } [ValidateGreatorThan(0)] public int Limit { get; set; } } ``` Or for more control you can use custom [Fluent Validation](/validation) validators. Validators are no-touch and invasive free meaning you can add them using a layered approach and maintain them without modifying the service implementation or DTO classes. Since they require an extra class We'd only use them on operations with side-effects e.g. **POST** or **PUT**, as **GET** requests tend to have minimal validation so throwing C# Exceptions typically requires less boilerplate. Here's an example of a validator you could have when creating a Booking: ```csharp public class CreateBookingValidator : AbstractValidator { public CreateBookingValidator() { RuleFor(r => r.StartDate).NotEmpty(); RuleFor(r => r.ShiftId).NotEmpty().GreaterThan(0); RuleFor(r => r.Limit).NotEmpty().GreaterThan(0); } } ``` Depending on the use-case instead of having separate `CreateBooking` and `UpdateBooking` DTOs you could re-use the same `StoreBooking` Request DTO to handle both operations. # Modular Startup Source: https://docs.servicestack.net/modular-startup ::: info For more information on the earlier Modular Startup in ServiceStack **v5.x** see our [Legacy Modular Startup](/modular-startup-legacy) docs ::: Taking advantage of C# 9 top level statements and .NET 10 [WebApplication Hosting Model](https://gist.github.com/davidfowl/0e0372c3c1d895c3ce195ba983b1e03d), ServiceStack templates by utilize both these features to simplify configuring your AppHost in a modular way. `Program.cs` becomes a script-like file since C# 9 top level statements are generating application entry point implicitly. ```csharp var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); app.UseHttpsRedirection(); } app.UseServiceStack(new AppHost()) app.Run(); ``` The application `AppHost` hooks into startup using `HostingStartup` assembly attribute. In ServiceStack templates, this uses the file name prefix of `Configure.*.cs` to help identify these startup modules. All ServiceStack's features are loaded using .NET's `HostingStartup`, including ServiceStack's `AppHost` itself that's now being configured in [Configure.AppHost.cs](https://github.com/NetCoreTemplates/web/blob/master/MyApp/Configure.AppHost.cs), e.g: ```csharp [assembly: HostingStartup(typeof(MyApp.AppHost))] namespace MyApp; public class AppHost() : AppHostBase("MyApp"), IHostingStartup { public void Configure(IWebHostBuilder builder) => builder .ConfigureServices(services => { // Configure ASP.NET Core IOC Dependencies }); public override void Configure() { // Configure ServiceStack, Run custom logic after ASP.NET Core Startup SetConfig(new HostConfig { }); } } ``` The use of Modular Startup does not change the AppHost declaration, but enables the modular grouping of configuration concerns. Different features are encapsulated together allowing them to be more easily updated or replaced, e.g. each feature could be temporarily disabled by commenting out its assembly HostingStartup's attribute: ```csharp //[assembly: HostingStartup(typeof(MyApp.AppHost))] ``` ## Module composition using `mix` This has enabled ServiceStack Apps to be easily composed with the features developers need in mind. Either at project creation with servicestack.net/start page or after a project's creation where features can easily be added and removed using the command-line [mix tool](/mix-tool) where you can view all available mix gists that can be added to projects with: :::sh x mix ::: .NET 10's idiom is incorporated into the [mix gist config files](https://gist.github.com/gistlyn/9b32b03f207a191099137429051ebde8) to adopt its `HostingStartup` which is better able to load modular Startup configuration without assembly scanning. This is a standard ASP .NET Core feature that we can use to configure Mongo DB in any ASP .NET Core App with: :::sh npx add-in mongodb ::: Which adds the `mongodb` gist file contents to your ASP .NET Core Host project: ```csharp using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; [assembly: HostingStartup(typeof(MyApp.ConfigureMongoDb))] namespace MyApp; public class ConfigureMongoDb : IHostingStartup { public void Configure(IWebHostBuilder builder) => builder .ConfigureServices((context, services) => { var mongoClient = new MongoClient(); IMongoDatabase mongoDatabase = mongoClient.GetDatabase("MyApp"); services.AddSingleton(mongoDatabase); }); } ``` As it's not a ServiceStack feature it can be used to configure ASP .NET Core Apps with any feature, e.g. we could also easily configure [Marten](https://martendb.io) in an ASP .NET Core App with: :::sh npx add-in marten ::: The benefit of this approach is entire modules of features can be configured in a single command, e.g. An empty ServiceStack App can be configured with MongoDB, ServiceStack Auth and a MongoDB Auth Repository with a single command: :::sh npx add-in auth auth-mongodb mongodb ::: Likewise, you can replace MongoDB with a completely different PostgreSQL RDBMS implementation by running: :::sh npx add-in auth auth-db postgres ::: ### Services and App Customizations Modular Startup configurations are flexible enough to encapsulate customizing ASP.NET Core's IOC and the built `WebApplication` by registering a `IStartupFilter` which is required by the Open API v3 Modular Configuration: :::sh npx add-in openapi3 ::: ```csharp [assembly: HostingStartup(typeof(MyApp.ConfigureOpenApi))] namespace MyApp; public class ConfigureOpenApi : IHostingStartup { public void Configure(IWebHostBuilder builder) => builder .ConfigureServices((context, services) => { if (context.HostingEnvironment.IsDevelopment()) { services.AddEndpointsApiExplorer(); services.AddSwaggerGen(); services.AddServiceStackSwagger(); services.AddBasicAuth(); //services.AddJwtAuth(); services.AddTransient(); } }); public class StartupFilter : IStartupFilter { public Action Configure(Action next) => app => { app.UseSwagger(); app.UseSwaggerUI(); next(app); }; } } ``` ### ConfigureAppHost Looking deeper, we can see where we're plugins are able to configure ServiceStack via the `.ConfigureAppHost()` extension method to execute custom logic on `AppHost` Startup: ```csharp [assembly: HostingStartup(typeof(MyApp.ConfigureAutoQuery))] namespace MyApp; public class ConfigureAutoQuery : IHostingStartup { public void Configure(IWebHostBuilder builder) => builder .ConfigureServices(services => { // Enable Audit History services.AddSingleton(c => new OrmLiteCrudEvents(c.GetRequiredService())); // For TodosService services.AddPlugin(new AutoQueryDataFeature()); // For Bookings https://docs.servicestack.net/autoquery-crud-bookings services.AddPlugin(new AutoQueryFeature { MaxLimit = 1000, //IncludeTotal = true, }); }) .ConfigureAppHost(appHost => { appHost.Resolve().InitSchema(); }); } ``` ### Customize AppHost at different Startup Lifecycles By default, any AppHost configuration is called before `AppHost.Configure()` is run, but to cater for all plugins, AppHost configurations can be registered at different stages within the AppHost's initialization: ```csharp public void Configure(IWebHostBuilder builder) => builder .ConfigureAppHost( beforeConfigure: appHost => /* fired before AppHost.Configure() */, afterConfigure: appHost => /* fired after AppHost.Configure() */, afterPluginsLoaded: appHost => /* fired after plugins are loaded */, afterAppHostInit: appHost => /* fired after AppHost has initialized */); ``` ### Removing Features The benefits of adopting a modular approach to AppHost configuration is the same as general organizational code structure which results in better decoupling and cohesion where it's easier to determine all the dependencies of a feature, easier to update, less chance of unintended side effects, easier to share standard configuration amongst multiple projects and easier to remove the feature entirely, either temporarily if needing to isolate & debug a runtime issue by: ```csharp // [assembly: HostingStartup(typeof(MyApp.ConfigureAuth))] ``` Or easier to permanently replace or remove features by either directly deleting the isolated `*.cs` source files or by undoing mixing in the feature using `mix -delete`, e.g: :::sh npx add-in -delete auth auth-db postgres ::: Which works similar to package managers where it removes all files contained within each mix gist. ::: info Please see the [Mix HowTo](https://gist.github.com/gistlyn/9b32b03f207a191099137429051ebde8#file-mix_howto-md) to find out how you can contribute your own gist mix features ::: ## Migrating to HostingStartup As we'll be using the new `HostingStartup` model going forward we recommend migrating your existing configuration to use them. To help with this you can refer to the [mix diff](https://github.com/ServiceStack/mix/commit/b56746622aa1879e3e6a8cbf835e634f05db30db) showing how each of the existing mix configurations were converted to the new model. As a concrete example, lets take a look at the steps used to migrate our Chinook example application [from NET5 using the previous `Startup : ModularStartup`, to .NET 6 `HostingStartup`](https://github.com/NetCoreApps/Chinook/commit/2758af9deae9c3aa910a27134f95167f7ec6e541). ### Step 1 Migrate your existing `ConfigureServices` and `Configure(IApplicationBuilder)` from `Startup : ModularStartup` to the top-level host builder in `Program.cs`. Eg ```csharp var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. // You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); app.UseHttpsRedirection(); } app.Run(); ``` ### Step 2 Move your `AppHost` class to a new `Configure.AppHost.cs` file. ### Step 3 Implement `IHostingStartup` on your AppHost with automatic initialization. Eg: ```csharp public void Configure(IWebHostBuilder builder) { builder.ConfigureServices(services => { // Configure ASP.NET Core IOC Dependencies }); } ``` ### Step 4 Declare `assembly: HostingStartup` for your `AppHost` in the same `Configure.AppHost.cs`. Eg: ```csharp [assembly: HostingStartup(typeof(Chinook.AppHost))] ``` ### Step 5 Migrate each existing modular startup class that implements `IConfgiureServices` and/or `IConfigureApp` to use `IHostingStartup`. Eg: ```csharp // net5.0 modular startup using ServiceStack; namespace Chinook; public class ConfigureAutoQuery : IConfigureAppHost { public void Configure(IAppHost appHost) { appHost.Plugins.Add(new AutoQueryFeature { MaxLimit = 1000, IncludeTotal = true }); } } ``` ```csharp // net8.0 modular startup using IHostingStartup using Microsoft.AspNetCore.Hosting; using ServiceStack; [assembly: HostingStartup(typeof(Chinook.ConfigureAutoQuery))] namespace Chinook; public class ConfigureAutoQuery : IHostingStartup { public void Configure(IWebHostBuilder builder) => builder .ConfigureServices(services => { services.AddPlugin(new AutoQueryFeature { MaxLimit = 1000, IncludeTotal = true }); }); } ``` > Remembering also that infrastructure like your `Dockerfile` or host will likely need the runtimes/SDKs updated as well. # ServiceStack's .NET Core Utility Belt Source: https://docs.servicestack.net/dotnet-tool Our `x` and `app` dotnet tools are a versatile invaluable companion for all ServiceStack developers where it's jam packed with functionality to power a number of exciting scenarios where it serves as a [Sharp App](https://sharpscript.net/docs/sharp-apps) delivery platform where they can be run as a .NET Core Windows Desktop App with `app` or as a cross-platform Web App launcher using `web` and we've already how it's now a [`#Script` runner](https://sharpscript.net/docs/sharp-scripts) with `x run` and into a [Live `#Script` playground](https://sharpscript.net/docs/sharp-scripts#live-script-with-web-watch) with `x watch`. These tools contains all the functionality ServiceStack Developers or API consumers need that can be used [Create ServiceStack projects](/dotnet-new), run [Gist Desktop Apps](https://sharpscript.net/sharp-apps/gist-desktop-apps) or generate typed endpoints for consuming ServiceStack Services by either [Add/Update ServiceStack References](/add-servicestack-reference) or by generating [gRPC client proxies](/grpc#grpc-clients). ## Install To access available features, install with: :::sh dotnet tool install --global x ::: ### Update Or if you had a previous version installed, update with: :::sh dotnet tool update -g x ::: ::: info Both `x` and `app` have equivalent base functionality, whilst `app` has superset [Windows-only Desktop features](/netcore-windows-desktop) ::: ::: info To update and download Add ServiceStack Reference dtos without .NET see [npx get-dtos](/npx-get-dtos) ::: ## Usage Then run `x` without any arguments to view Usage: :::sh x ::: ```txt Usage: x new List available Project Templates x new