As it is currently designed, the MVC framework places all URL Routing rules into global.asax.
Personally, I feel that many applications will have dozens, if not hundreds of URL routing rules, so the first thing I did was create a HTTPModule and move the URL routing rules out of global.asax.
This worked great, but I find the concept of hard coding configuration into the source code rather primitive, so I began implementing a custom configuration section into web.config to handle URL routing.
Initial development went great, and it was not long before I had this in my web.config:
<RouteTable>
<Routes>
<addRoute Url="[controller]/[action]/[postId]" Defaults="action=Index,postId=(string)null"/>
<addRoute Url="Default.aspx" Defaults="controller=Home,action=Index,id=(string)null"/>
</Routes>
</RouteTable>
The only caveat? My dynamic route building code did not work.
I had assumed that because Route.Defaults was an object type, it would be smart enough to let me stuff a key/value Dictionary into it containing the defaults values.
However, Route.Defaults only accepts an anonymous type, as you can see here in the debugger:

The C# compiler converts these anonymous types to strongly typed classes during compile time, so the Route class must rely on reflection to figure out what properties were created. In my opinion this is a rather inelegant abuse of a new technology, when a simply dictionary would have sufficed just fine.
A little googling found a blog post from Eilon Lipton championing this technique, and why they used in the MVC framework.
Granted, I am new to C# 3.0, and I don't fully understand all of its new features. But for the life of me, I cannot figure out how to construct an anonymous class during runtime, and if you cannot*, then there is no way to dynamically build route tables with the MVC framework as it is currently designed.
And that, I must say, is disappointing.
* Please tell me how to do this if its possible!
2 comments:
As it uses reflection you can create a class with the relevant properties (controller, action, id) and pass that in. Asthe reflection is just looking for properties with those names then it will pick up the properties in your class.
Sorry, to expand on that, you could use the codedom stuff to create a class at runtime with the relevant properties.
And yes, you would hope it would be easier than that!
Post a Comment