| Adding HttpMethodConstraint to ASP.NET MVC Routes |
| Friday, February 27 2009 |
|
I was doing some stuff with ASP.NET MVC the other day (as a spike to implement REST) when I realized I wanted to setup two routes for the exact same URL where both routes would use the same controller, but invoke a different method on that controller based on the HTTP verb from the request. For example, if the request for http://mysite.com/api/users is with a GET, I want to invoke the List() method in the UsersController, but if the request is with a POST, I want to invoke the Create() method instead.
After poking around and not finding what I needed, I pinged Nate who pointed me to HttpMethodConstraint. Using HttpMethodConstraint is pretty easy, and here’s the code I ended up with:
routes.MapRoute(
"Users-GET",
"api/users",
new { controller = "Users", action = "List" },
new { httpMethod = new HttpMethodConstraint("GET") }
);
routes.MapRoute(
"Users-POST",
"api/users",
new { controller = "Users", action = "Create" },
new { httpMethod = new HttpMethodConstraint("POST") }
);
As you can see, both routes map to the “api/users” URL, and both use the “Users” controller, but the first one invokes the List() method if GET is used while the second route invokes Create() when POST is used.
Like I said, this is pretty easy and I like that it’s very clear the intent of what is supposed to happen.
