I’m developing an ASP.NET MVC Web Api 2 with .NET Framework 4.5.1 and C#.
I have these entities in database:
- Users, which are members of groups.
- Groups.
- Messages. Users can sent messages to a groups.
I have this route:
config.Routes.MapHttpRoute(
name: "GroupMessagesApiRoute",
routeTemplate: "api/groups/{groupId}/messages/{messageId}",
defaults: new
{
controller = "GroupMessages",
messageId = RouteParameter.Optional
}
);
With this route I can get all group’s messages and one message, with {messageId}
, sent to {goupId}
.
But now I want to get all messages with an ID greater than {messageId}
. How can I do that?
I’ve thought to create another route like this one:
config.Routes.MapHttpRoute(
name: "GroupMessagesApiRoute",
routeTemplate: "api/groups/{groupId}/messages/{messageId}/unread",
defaults: new
{
controller = "GroupUnreadMessages"
}
);
I will need another controller, `GroupUnreadMessages, to get all unread messages. But I don’t know if this is the better approach.
7
For the greater than certain id query, probably clearest way is to use query strings. Something like
api/groups/{groupId}/messages?id=gt:50
The “gt:50” is just an idea, it is easy to parse but it can be anything you like (there is no > symbol in query strings, it is key value so you need to add your own operators if you want complex queries.
Your “messages” resource should return a sub-set of messages if it gets a query string, where as without the query string you get back all messages.
For all unread messages you could add another query string such as
api/groups/{groupId}/messages?status=unread
or you could make it part of the hierarchy.
api/groups/{groupId}/messages/unread
Depends on what makes sense for your resource hierarchy.