我目前正在为应用程序编写一个新闻文章方面,并将新的路由(针对新文章)添加到我的RouteTable中,这看起来很好,但是这些路由是不可到达的?
我使用的代码如下:
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" });
}正如我前面所说的,新的Url被添加到RouteTable.Routes中,但是我无法到达页面。重新启动后,它将由RegisterRoutes在Global.asax中拾取并正常工作。
任何你能提供的光线都是很棒的,因为我想在不强制重新启动应用程序的情况下实现这一点。
编辑
这是我的RegisterRoutes 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
);
}发布于 2012-02-04 17:00:54
问题是调用RouteTable.MapRoute会将路由添加到表的末尾。默认路由通常是添加到表中的最后一条路由,但是由于您在构建路由表之后动态调用RouteTable.MapRoute,默认路由在到达新添加的路由之前被击中。
我对这个问题的解决办法如下。
public static void AddContentRoute(this RouteCollection routes, Data.UrlMap map, bool needsLock = false)
{
var route = new Route(map.Url, new MvcRouteHandler());
route.Defaults = new RouteValueDictionary(new
{
controller = "Content",
action = "Display",
id = map.Id,
type = map.Type
});
if (needsLock)
{
using (routes.GetWriteLock())
{
routes.Insert(0, route);
}
}
else
{
routes.Insert(0, route);
}
}这实际上是做RouteTable.MapRoute所做的,但是将路由插入到表的顶部而不是末尾。
如果您有其他需要位于表顶部的路由,则可能需要修改此解决方案。
发布于 2012-01-31 16:01:22
你为什么要在飞行中创造一条路线?当应用程序自己重新启动应用程序时,所有这些路由都需要重新创建才能正常工作,这不是没有意义的吗?
为什么不创建一个只处理对cms的所有请求的路由呢?
routes.MapRoute("CmsPage", "{page}", new { controller = "Cms", action = "Index"}, new [] { "Web.Controllers.CmsController" });如果您这样做是为了避免与应用程序中的其他路由/控制器发生冲突,那么始终可以在所有cms生成的页面前加上页面。我这样做是为了一个CMS网站,我现在正在创建。
routes.MapRoute("CmsPage", "pages/{page}", new { controller = "Cms", action = "Index"}, new [] { "Web.Controllers.CmsController" });您在控制器中的操作将与此类似
public ActionResult Index(string page)
{
// logic to load page
return View();
}https://stackoverflow.com/questions/9082581
复制相似问题