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:
routes.MapRoute(
"Default",
"{id}",
new { controller = "Home", action = "Index" }
);
Now a request of the form /About
will be routed to the Index
action of the Home
controller and passed id=About
as argument:
public ActionResult Index(string id)
{
// if the request was /About, id will equal to About here
...
}
精彩评论