Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST Routing in ServiceStack

Tags:

servicestack

I just start to learn REST and ServiceStack and there's something about Route that I just can't quite understand. For example if we take the very basic HelloWorld example from GitHub tutorial and re-write it to return collection of User objects. Here is example:

public User
{
    public string Name;
    public string Address;
    public int Age;
}


// Hello - request object without [Route] attribute
public class Hello
{
   public string Name { get; set; }
}

public class HelloResponse
{
   public IEnumerable<User> Result {get;set;}
}


public class HelloService : Service
{
   public object Any(Hello request)
   {
       return new HelloResponse { // Collection of User object };
   }
} 

now everything working right and no problems here. But now I want to add another routing url like: /Hello/{name}/Address

Actually this call (GET) to this url will return a single User selected by Age parameter. How I can do this ? Should I add another Service ? And if the url will be:

/Hello/{name}/{age}/Address

It seems I don't understand something.....

like image 617
Alex F Avatar asked Oct 22 '22 22:10

Alex F


1 Answers

See this earlier answer for details about Routing in ServiceStack. The Smart Routing section in ServiceStack's New API explains further options and different precedence.

There are a few problems with your example. First ServiceStack text serializers only support public properties so you need to change your User Model to use public properties instead of fields, e.g:

public User
{
    public string Name { get; set; }
    public string Address { get; set; }
    public int Age { get; set; }
}

Next, Interfaces on DTOs are a bad idea as there's no good reason for it. They're still supported but you can end up with undesirable results. Use a concrete collection like a List<T> which provides more utility, e.g:

public class HelloResponse
{
    public List<User> Results { get; set; }
}

Also the routes should match the property names on your DTO exactly, they are case-insensitive when matching against the Request Path, but they need to map to an exact property name, e.g:

/Hello/{Name}/{Age}/Address
like image 136
mythz Avatar answered Oct 27 '22 22:10

mythz