I'm working on my first project using asp.net MVC. 

I came across what is probably a common desire amongst MVC developers: the ability to serve a client a response type of its choice.  I wanted to do this by specifying the desired type in the URL and keeping the URLs pretty.

Here are how I wanted the routes to look:

  • /Home/Index - return HTML view
  • /Home/Index.xml - return xml view
  • /Home/Index.json - return json view
With the routing with asp.net MVC, this was simple.

I added this to RegisterRoutes after the default route in global.asax:
routes.MapRoute(
"SpecifyType",
"{controller}/{action}.{responseType}/{id}",
new { controller = "Home", action = "Index", id = "", responseType = "html" }
);
I also changed the default route to this:

routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "", responseType = "html" },
new { action = @"\w+" }
);
Now in the controllers you can check for the desired response type as such:

string responseType = RouteData.Values["responseType"]

This could be encapsulated into a controller base class to make things cleaner.  I'll leave that to the reader.

 kick it on DotNetKicks.com