Can I store ASP.NET MVC routes in web.config?

I am looking for a way to store routing information in my web.config file in addition to the Global.asax class. Routes stored in the configuration file must have higher priority than those added programmatically.

I did my search, but closest I can find the RouteBuilder on Codeplex ( http://www.codeplex.com/RouteBuilder ), but this does not work with the RTM version of MVC. Is there a solution compatible with final 1.0?

+2
source share
2 answers

I can’t guarantee that 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 remove the DefaultsType class. This was necessary because the default system was much more complicated in CTP than in RTM.

Edit: Oh and add using System.Web.Routing;to the beginning and make sure you've added System.Web.Mvcand System.Web.Routingincorporated by reference.

+1
source

All Articles