GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Routing Routing
Demis Bellot edited this page
This page has moved to docs.servicestack.net/routingWithout any configuration required, ServiceStack already includes pre-defined routes for all services in the format:
e.g. the pre-defined url to call a JSON 'Hello' Service is: In its most basic form, a Route is just any string literal attributed on your Request DTO: which matches: Routes can also have variable place-holders: matches: 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. Using a route with a wild card path like: matches any number of variable paths: Another good use-case for when to use wildcard routes. Use the [FallbackRoute("/{Path}")] public class Fallback { public string Path { get; set; } } This will match any unmatched route from the root path (e.g. The Fallback route is useful for HTML5 Single Page App websites handling server requests of HTML5 pushState pretty urls. 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 { ... } You can use the [Route("/contacts/{Id}/{ignore}", "GET")] public class GetContacts { ... } Will match on You can also use a Fluent API to register ServiceStack Routes by adding them in your and to match only GET request for In addition to using the standard 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 Also related to this is registering Auto routes via the Routes.AddFromAssembly extension method, where this single call: 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. The default convention registers routes based on the Request DTO Name, whether it has an Id property and what actions were implemented. These conventions are configurable where you can now adjust/remove the existing rules or add your own to the pre-defined rules in RouteNamingConventions = new List<RouteNamingConventionDelegate> { RouteNamingConvention.WithRequestDtoName, RouteNamingConvention.WithMatchingAttributes, // defaults: PrimaryKeyAttrubute RouteNamingConvention.WithMatchingPropertyNames, // defaults: Id, IDs } The existing rules can be further customized by modifying the related static properties, e.g: RouteNamingConvention.PropertyNamesToMatch.Add("UniqueId"); RouteNamingConvention.AttributeNamesToMatch.Add("DefaultIdAttribute"); Which will make these request DTOs: class MyRequest1 { public UniqueId { get; set;} } class MyRequest2 { [DefaultId] public CustomId { get; set;} } Generate the following routes: See the implementation of RouteNamingConvention for examples of how to add your own auto-generated route conventions. Routes attributes can also be added dynamically but as Services are auto-registered before public class AppHost : AppHostBase { public AppHost() { typeof(MyRequest) .AddAttributes(new RouteAttribute("/myrequest")) .AddAttributes(new RouteAttribute("/myrequest/{UniqueId}")); } } You can customize existing routes by overriding public class AppHost : AppHostBase { //... public override RouteAttribute[] GetRouteAttributes(Type requestType) { var routes = base.GetRouteAttributes(requestType); routes.Each(x => x.Path = "/api" + x.Path); return routes; } } This is described in more detail on the New API Design wiki but the weighting used to select a route is based on:
The following HTTP Request: Will match the following Route definitions in order from highest precedence to lowest: [Route("/content/v1/literal/slug", "GET")] [Route("/content/v1/literal/slug")] [Route("/content/v1/literal/{ignore}", "GET")] [Route("/content/{ignore}/literal/{ignore}", "GET")] [Route("/content/{Version*}/literal/{Slug*}", "GET")] [Route("/content/{Version*}/literal/{Slug*}")] [Route("/content/{Slug*}", "GET")] [Route("/content/{Slug*}")] See the RestPathTests.cs and Smart Routing section on the wiki for more examples. If you use [Route("/reqstars/search", "GET")] [Route("/reqstars/aged/{Age}")] public class SearchReqstars : IReturn<ReqstarsResponse> { public int? Age { get; set; } } var relativeUrl = new SearchReqstars { Age = 20 }.ToGetUrl(); var absoluteUrl = new SearchReqstars { Age = 20 }.ToAbsoluteUri(); relativeUrl.Print(); //= /reqstars/aged/20 absoluteUrl.Print(); //= http://www.myhost.com/reqstars/aged/20 The Email Contacts demo shows an example of using the above Reverse Routing extension methods to populate routes for HTML Forms and Links in Razor Views. new RequestDto().ToPostUrl(); new RequestDto().ToPutUrl(); new RequestDto().ToDeleteUrl(); new RequestDto().ToOneWayUrl(); new RequestDto().ToReplyUrl(); Request DTO's can customize urls used in Service Clients or any libraries using ServiceStack's typed Reverse Routing by having Request DTO's implement IUrlFilter. ServiceStack's Stripe Gateway takes advantage of ServiceStack's typed Routing feature to implement its Open-Ended, Declarative Message-based APIs with minimal effort. In order to match Stripe's unconventional syntax for specifying arrays on the QueryString of their 3rd party
REST API we use [Route("/customers")] public class GetStripeCustomers : IGet, IReturn<StripeCollection<Customer>>, IUrlFilter { public GetStripeCustomers() { Include = new[] { "total_count" }; } [IgnoreDataMember] public string[] Include { get; set; } public string ToUrl(string absoluteUrl) { return Include == null ? absoluteUrl : absoluteUrl.AddQueryParam("include[]", string.Join(",", Include)); } }
Which when sending the Request DTO: var response = client.Get(new GetStripeCustomers()); Generates and sends the relative url: Which has the effect of populating the Most of the metadata ServiceStack knows about your services are accessible internally via 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.
Clone this wiki locally |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |