Defining Routes

Routes are defined in the Load() method. In order to define a route you need to specify a Method + Pattern + Action.

 public class ProductsHttpService : IHttpService
 {
     public void Load(IHttpServiceBuilder builder)
     {
         builder.Get["/products/{id}"] = async request =>
         {
             // Do something
         };
     }
 }

Method

The Method is the HTTP method that is used to access the resource. You can handle GET, POST, PUT, PATCH and DELETE methods. The IHttpServiceBuilder interface contains a definition for each of these methods.

Pattern

The Pattern declares the application-relative URL that the route answers to.

  • Literal segment, /some, requires an exact match.
  • Capture segment, /{name}, captures whatever is passed into the given segment.
  • Capture optional segment, /{name?}, by adding ? at the end of the segment name the segment can be made optional.
  • Capture optional/default segment, /{name?unnamed}, by adding a value after ? we can turn an optional segment into a segment with a default value.
  • RegEx segment, /(?<id>[\d]{1,2}), using Named Capture Grouped Regular Expressions, you can get a little more control out of the segment pattern.
  • Greedy segment, /{name*}, by adding * to the end of the segment name, the pattern will match any value from the current forward slash onward.
  • Multiple captures segment, /{file}.{extension} or /{file}.ext, a segment containing a mix of captures and literals.

Pattern segments can be combined, in any order, to create a complex Pattern for a route.

Note

It’s worth noting that capture segments are greedy, meaning they will match anything in the requested URL until another segment matches or until the end of the URL is reached. Sometimes you may end up with two routes which end up giving a positive match. Each pattern has a score which is used to resolve the conflicts. But we do not recommend to use conflicted routes.

Action

A route Action is the behavior which is invoked when a request is matched to a route. It is represented as a delegate of type Func<IHttpRequest,Task<object>> where the input argument is an information about request (IHttpRequest) and the result is a task (Task<object>) to retrieving response. The response can be any model.