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


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?


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.


look at this: http://weblogs.asp.net/fredriknormen/archive/2008/03/11/asp-net-mvc-framework-2-define-routes-in-web-config.aspx

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »