MVC Greedy route mapping and custom route handler

By on (tags: mvc, categories: code)

I’m learning to love MVC mostly for it’s flexibility. In a recent situation, I wanted to have a generic controller that will perform CRUD (Create Read Update Delete) operations on an entity. By default, this is not handled, but with a little custom code, it turned out to be quite easy.

Let me describe the use case first. The idea is to have a controller (let’s call it Foo) that looks more or less like this:

The problem here was, that out of the box, this is not supported. I’d have to create an separate controller for each T and as in my case, the T was out of my control, and thus that was not an option.

So, how to handle that? Well, there are 2 things to be utilized here: greedy route mapping and custom route handler. First, here’s one of the ways to hook it all up:


Nothe the * in the path url section. What it does is that it grabs the whole url part that follows “Foo/{action}”. So in case of “Foo/Edit/bar/buz/bleach” the path part is resolved to “bar/buz/bleach” whereas without the * it would have been resolved to “bar” and the routing handler would continue to search for the remaining parts (buz and bleach would need to be mapped to something).

The other interesting thing here is the FooRouteHandler and here’s how it looks like:

And the FooHttphandler:

(yes, you guessed right, it’s a cms-ish framework)

Note that I am able utilize this mechanism, because I can determine the page type based on the url (or in general based on anything that comes along with HttpContext) – it would be hard to accomplish this otherwise.