我有一个控制器动作,如下所示:
public ActionResult Content(string slug)
{
var content = contentRepository.GetBySlug(slug);
return View(content);
}
我希望将这种网址发送到我的行动:
这是我的RegisterRoutes方法:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Page", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "GetContent",
url: "{slug}",
defaults: new { controller = "Page", action = "Content", slug = "" }
);
}
但它不起作用,我做错了什么?
谢谢,
答案 0 :(得分:2)
1将slug路线置于默认路线上方,如果没有,则永远不会进入slug路线
2你的slug不能为空,如果为空,则网址为http://localhost/它必须是默认路由
routes.MapRoute(
name: "slug",
url: "{slug}",
defaults: new { controller = "Home", action = "show" },
constraints: new{ slug=".+"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
我认为不要选择“内容”作为动作名称,因为基类中有一个内容方法
答案 1 :(得分:1)
对于动态路线,您可以使用:
routes.MapRoute(
name: "PageName",
url: "{pageName}",
defaults: new { controller = "Page", action = "Content", pageName = "defaultPage" }
);
将使用“Page”控制器中的Action“Content”映射到〜/ Pagename:
public ActionResult Content(string pageName)
{
ViewBag.Message = pageName;
return View();
}