Skip to content
Demis Bellot edited this page Jul 22, 2013 · 20 revisions

Pre-defined Routes

Without any configuration required, ServiceStack already includes pre-defined routes for all services in the format:

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

e.g. the pre-defined url to call a JSON 'Hello' Service is:

/json/reply/hello

SOAP Web Service urls

/api?/[soap11|soap12]

Custom Routes

In its most basic form, a Route is just any string literal attributed on your Request DTO:

[Route("/hello")]
public class Hello { ... }

which matches:

/hello
/hello?Name=XXX

Variable place-holders

Routes can also have variable place-holders:

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

matches:

/hello/foo

And will populate the public property Name on the Request DTO with foo.

Note: The QueryString, FormData and HTTP Request Body isn't apart of the Route (i.e. only the /path/info is) but they can all be used in addition to every web service call to further populate the Request DTO.

Wildcard paths

Using a route with a wild card path like:

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

matches any number of variable paths:

/hello
/hello/name
/hello/my/name/is/ServiceStack    //Name = my/name/is/ServiceStack

Another good use-case for when to use wildcard routes.

Fallback Route

Use the FallbackRoute attribute to specify a fallback route starting from the root path, e.g:

[FallbackRoute("/{Path}")]
public class Fallback
{
    public string Path { get; set; }
}

This will match any unmatched route from the root path (e.g. /foo but not /foo/bar) that's not handled by CatchAll Handler or matches a static file. You can also specify a wildcard path e.g. [FallbackRoute("/{Path*}")] which will handle every unmatched route (inc. /foo/bar).

Fallback routes are useful for HTML5 Single Page App websites handling server requests of HTML5 pushState pretty urls.

Limiting to HTTP Verbs

If not specified Routes will match All HTTP Verbs. You can also limit Routes to individual Verbs, this lets you route the same path to different services, e.g:

[Route("/contacts", "GET")]
[Route("/contacts/{Id}", "GET")]
public class GetContacts { ... }

[Route("/contacts", "POST PUT")]
[Route("/contacts/{Id}", "POST PUT")]
public class UpdateContact { ... }

[Route("/contacts/{Id}", "DELETE")]
public class DeleteContact { ... }

Fluent API

You can also use a Fluent API to register ServiceStack Routes by adding them in your AppHost.Configure():

Routes
  .Add<Hello>("/hello")
  .Add<Hello>("/hello/{Name}");

and to match only GET request for /Customers?Key=Value and /Customers/{Id}:

Routes
    .Add<GetContact>("/Contacts", "GET")
    .Add<GetContact>("/Contacts/{ContactId}", "GET");

Content Negotiation

In addition to using the standard Accept HTTP Header to retrieve the response a different format, you can also request an alternative Content-Type by appending ?format=ext to the query string, e.g:

Or by appending the format .ext to the end of the route, e.g:

This is enabled on all custom routes and works for all built-in and user-registered formats. It can be disabled by setting Config.AllowRouteContentTypeExtensions = false.

Auto Register Convention-based Routes

Also related to this is registering Auto routes via the Routes.AddFromAssembly extension method, where this single call:

Routes.AddFromAssembly(typeof(FooService).Assembly)

Goes through and scans all your services (in the Assemblies specified) and registers convention-based routes based on all the HTTP methods you have implemented.

E.g. With the following Services:

public class Foo
{
	public int Id { get; set; }
}
public class Bar {}

public class FooService : Service {    	
	public object Get(Foo request) { ... }
	public object Post(Foo request) { ... }
	public object Get(Bar request) { ... }
}

Adding this in your AppHost.Configure():

Routes.AddFromAssembly(typeof(FooService).Assembly);

Is equivalent to manually adding these route registrations:

Routes.Add<Foo>("/foo", "GET POST");
Routes.Add<Foo>("/foo/{Id}", "GET POST");
Routes.Add<Bar>("/bar", "GET");

Routing Resolution Order

This is described in more detail on the [New API Design wiki][4] but the weighting used to select a route is based on:

  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)

See the Smart Routing section on the wiki for examples.

Great Performance

Since Routing in ASP.NET MVC can be slow when you have a large number of Routes, it's worthwhile pointing out ServiceStack's Routing implementation is implemented with hash lookups so doesn't suffer the linear performance regression issues you might have had with MVC. So you don't have to worry about degraded performance when registering a large number of Routes.

Community Resources



  1. Getting Started
    1. Create your first webservice
    2. Your first webservice explained
    3. ServiceStack's new API Design
    4. Designing a REST-ful service with ServiceStack
    5. Example Projects Overview
  2. Reference
    1. Order of Operations
    2. The IoC container
    3. Metadata page
    4. Rest, SOAP & default endpoints
    5. SOAP support
    6. Routing
    7. Service return types
    8. Customize HTTP Responses
    9. Plugins
    10. Validation
    11. Error Handling
    12. Security
  3. Clients
    1. Overview
    2. C# client
    3. Silverlight client
    4. JavaScript client
    5. Dart Client
    6. MQ Clients
  4. Formats
    1. Overview
    2. JSON/JSV and XML
    3. ServiceStack's new HTML5 Report Format
    4. ServiceStack's new CSV Format
    5. MessagePack Format
    6. ProtoBuf Format
  5. View Engines 4. Razor & Markdown Razor
    1. Markdown Razor
  6. Hosts
    1. IIS
    2. Self-hosting
    3. Mono
  7. Advanced
    1. Configuration options
    2. Access HTTP specific features in services
    3. Logging
    4. Serialization/deserialization
    5. Request/response filters
    6. Filter attributes
    7. Concurrency Model
    8. Built-in caching options
    9. Built-in profiling
    10. Messaging and Redis
    11. Form Hijacking Prevention
    12. Auto-Mapping
    13. HTTP Utils
    14. Virtual File System
    15. Config API
    16. Physical Project Structure
    17. Modularizing Services
  8. Plugins
    1. Sessions
    2. Authentication/authorization
    3. Request logger
    4. Swagger API
  9. Tests
    1. Testing
    2. HowTo write unit/integration tests
  10. Other Languages
    1. FSharp
    2. VB.NET
  11. Use Cases
    1. Single Page Apps
    2. Azure
    3. Logging
    4. Bundling and Minification
    5. NHibernate
  12. Performance
    1. Real world performance
  13. How To
    1. Sending stream to ServiceStack
    2. Setting UserAgent in ServiceStack JsonServiceClient
    3. ServiceStack adding to allowed file extensions
    4. Default web service page how to
  14. Future
    1. Roadmap
Clone this wiki locally