I am working on a site where the user is going to add pages to the site, and I was trying to use routing to immediately have the page available after creation.
For example, the user may create an About page, and right now I put some logic in the controller when the page is added.
if (ModelState.IsValid)
{
context.Pages.Add(page);
context.SaveChanges();
RouteTable.Routes.MapRoute(page.Name, page.Url,
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
return RedirectToAction("Index");
}
But when I create the About page with About as the url and then try to go to /About, I get a 404 error.
Is it possible to add routes outside of the Application_Start?
You should avoid defining any routes in controller actions. For your scenario you could define the following route:
Now a request of the form
/Aboutwill be routed to theIndexaction of theHomecontroller and passedid=Aboutas argument: