Thursday, November 19, 2009

Using ASP.Net MVC Framework to build a highly RESTful Web Service

I dreamed this whole thing and implemented it on my own over a year ago.

Download and install ASP.Net MVC Framework.

See steps 7 -9 of previous post for tweaking IIS.

See the RegisterRoutes method below.

"EntryPoint" is a concrete action method on a abstract base class. It performs common parameter massaging, environment intialization and authentication stuff then routes the request to the appropriate abstract Get(), Put(), Post(), Delete() or Head() method implemented by the current Controller subclass. It does this via a switch block driven by the value of "httpMethod" obtained thusly: string httpMethod = HttpContext.Request.HttpMethod.ToUpper();


public static void RegisterRoutes(RouteCollection routes) {

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

Route route;

route = new Route("Help", new MvcRouteHandler());
route.Defaults = new RouteValueDictionary(new { controller = "Help", action = "Index" });
RouteTable.Routes.Add(route);

route = new Route("{controller}/{id}.{format}", new MvcRouteHandler());
route.Defaults = new RouteValueDictionary(new { action = "EntryPoint" });
route.Constraints = new RouteValueDictionary(new { format = @"json|pox|xhtml" });
RouteTable.Routes.Add(route);

route = new Route("{controller}.{format}", new MvcRouteHandler());
route.Defaults = new RouteValueDictionary(new { action = "EntryPoint" });
route.Constraints = new RouteValueDictionary(new { format = @"json|pox|xhtml", id = "" });
RouteTable.Routes.Add(route);

route = new Route("{controller}/{id}", new MvcRouteHandler());
route.Defaults = new RouteValueDictionary(new { action = "EntryPoint", format = "xhtml" });
RouteTable.Routes.Add(route);

route = new Route("{controller}", new MvcRouteHandler());
route.Defaults = new RouteValueDictionary(new { action = "EntryPoint", format = "xhtml", id = "" });
RouteTable.Routes.Add(route);

route = new Route("", new MvcRouteHandler());
route.Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index" });
RouteTable.Routes.Add(route);

}

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.

C# Sucks!

JK!! Seriously, though, somewhere around C#-3 we should have inculcated ourselves with the question: "Does 'CAN' == 'SHOULD...