I am currently writing a news article aspect to an application and I adding the new route (for the new article) to my RouteTable, which appears to add fine, but the routes are unreachable?
The code I am using is as follows:
var routes = RouteTable.Routes;
using (routes.GetWriteLock())
{
var url = contentHelper.GetPageUrl(page);
routes.MapRoute(page.Id.ToString(), url, new { controller = "Cms", action = "Index", id = url }, new[] { "Web.Controllers.CmsController" });
}
The new Url, as I previously said, is added to the RouteTable.Routes but I cant get to the page. After a restart it is picked up by RegisterRoutes in the Global.asax and works fine.
Any light that you can shed on this would be great, as I want to achieve this without forcing an app restart
EDIT
This is the RegisterRoutes from my global.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("LogOff", "LogOff", new { controller = "Account", action = "LogOff" });
routes.MapRoute(
"News", // Route name
"News/",// URL with parameters
new { controller = "NewsPage", action = "Index" }, // Parameter defaults
new[] { "Web.Controllers.NewsController" }
);
//register all content pages
var urls = new ContentPageHelper().GetAllUrls();
foreach (var url in urls)
{
routes.MapRoute(url.Key.ToString(), url.Value, new { controller = "Cms", action = "Index", id = url.Key }, new[] { "Web.Controllers.CmsController" });
}
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",// URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
The issue is that calling
RouteTable.MapRouteadds the route to the end of the table. Your default route is generally the last route to be added to the table, but since you are dynamically callingRouteTable.MapRouteafter you have already built your route table, the default route is being hit before it reaches your newly added route.My solution to this problem was as follows.
This essentially does what
RouteTable.MapRoutedoes, but inserts the route to the top of the table instead of the end.If you have other routes that need to sit at the top of the table you may want to modify this solution.