Restful Routing with ASP MVC Preview 2

There is still very little documentation available for ASP MVC 2, and I had a bit of trouble finding out how to put HTTP method constraints on routes. After a bit of poking around I found out that the Method value was changed to httpMethod. I generally follow the convention that my controller is named the same as my resource. For instance, a resource named “Rates” would have a Rates controller. I use this little utility method to map the REST routes for the Rates resource.

public class GlobalApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        MapResource(routes, "Rates");
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }

    protected static void MapResource(RouteCollection routes, string resourceName)
    {

        routes.Add(new Route(resourceName, new MvcRouteHandler())
        {
            Defaults = new RouteValueDictionary(
                new { controller = resourceName, action = "List" }),
            Constraints = new RouteValueDictionary(
                new { httpMethod = "GET" }),
        });

        routes.Add(new Route(resourceName, new MvcRouteHandler())
        {
            Defaults = new RouteValueDictionary(
                new { controller = resourceName, action = "Create" }),
            Constraints = new RouteValueDictionary(
                new { httpMethod = "PUT" }),
        });

        routes.Add(new Route(resourceName + "/{id}", new MvcRouteHandler())
        {
            Defaults = new RouteValueDictionary(
                new { controller = resourceName, action = "Read" }),
            Constraints = new RouteValueDictionary(
                new { httpMethod = "GET" }),
        });

        routes.Add(new Route(resourceName + "/{id}", new MvcRouteHandler())
        {
            Defaults = new RouteValueDictionary(
                new { controller = resourceName, action = "Update" }),
            Constraints = new RouteValueDictionary(
                new { httpMethod = "POST" }),
        });

        routes.Add(new Route(resourceName + "/{id}", new MvcRouteHandler())
        {
            Defaults = new RouteValueDictionary(
                new { controller = resourceName, action = "Delete" }),
            Constraints = new RouteValueDictionary(
                new { httpMethod = "DELETE" }),
        });
    }
}

It’s pretty basic, but it keeps your code DRY and saves time if you’re doing simple REST routes for a few different models.

Posted by Scott Tue, 15 Apr 2008 21:30:00 GMT