views:

478

answers:

2

I'm looking for a method of storing routing information in my web.config file in addition to the Global.asax class. The routes stored in the configuration file would need to take higher precedence than those added programmatically.

I've done my searching, but the closest I can come up with is the RouteBuilder on Codeplex (http://www.codeplex.com/RouteBuilder), but this doesn't work with the RTM version of MVC. Does a solution out there exist compatible with the final 1.0?

Thanks, Brian

+1  A: 

I can't guarantee the following code will work, but it builds :) Change the Init method in RouteBuilder.cs to the following:

    public void Init(HttpApplication application)
    {                  
        // Grab the Routes from Web.config
        RouteConfiguration routeConfig = 
            (RouteConfiguration)System.Configuration.ConfigurationManager.GetSection("RouteTable");

        // Add each Route to RouteTable
        foreach (RouteElement routeElement in routeConfig.Routes)
        {
            RouteValueDictionary defaults = new RouteValueDictionary();

            string[] defaultsArray = routeElement.Defaults.Trim().Split(',');

            if (defaultsArray.Length > 0)
            {
                foreach (string defaultEntry in defaultsArray)
                {
                    string[] defaultsEntryArray = defaultEntry.Trim().Split('=');

                    if ((defaultsEntryArray.Length % 2) != 0)
                    {
                        throw new ArgumentException("RouteBuilder: All Keys in Defaults must have values!");
                    }
                    else
                    {
                        defaults.Add(defaultsEntryArray[0], defaultsEntryArray[1]);
                    }
                }
            }
            else
            {
                throw new ArgumentException("RouteBuilder: Defaults value is empty or malformed.");
            }

            Route currentRoute = new Route(routeElement.Url, defaults, new MvcRouteHandler());
            RouteTable.Routes.Add(currentRoute);
        }
    }

Also, feel free to delete the DefaultsType class. It was needed because the defaults system was much more complicated back in CTP than in RTM.

Edit: Oh and add using System.Web.Routing; to the top and make sure you add System.Web.Mvc and System.Web.Routing as references.

Jeff Mc