我正在使用C#MVC。
我有一个看起来像这样的动作。
public class CustomController : Controller
{
public ActionResult CustomPage(int customPageId)
{
var model = new CustomPageViewModel()
{
customPageId = customPageId
};
return View(model);
}
}
我希望能够点击此操作,但使用其他路线。例如,我希望Home / Index实际执行此操作,但要在URL中报告其Home / Index。
我的自定义页面存储在数据库中,告诉它有什么路由,如何以编程方式为我的页面创建路径并让MVC执行所需的操作?
由于这是一个基于CMS的系统,我不想创建一个Home / Index控制器和动作,因为用户可以选择他们想要的任何路线。
谢谢,汤姆
答案 0 :(得分:0)
仅供参考:我有点想到这一点。不幸的是路由是在应用程序启动时定义的,所以如果我想在应用程序运行时设置新路由,我必须强制重启...
以下是我用来设置路线的代码,以帮助其他人。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var pageList = new PageService().Get();
foreach (var page in pageList)
{
var targetRoute = string.Format("{1}/{2}", page.PageArea, page.PageController, page.PageAction);
if (!string.IsNullOrWhiteSpace(page.PageArea))
targetRoute = string.Format("{0}/{1}/{2}", page.PageArea, page.PageController, page.PageAction);
routes.MapRoute(
string.Format("PageBuilder_{0}", page.PageId),
targetRoute,
new { area = "Builder", controller = "Build", action = "Index", pageId = page.PageId }
);
}
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}