如何用连字符实现asp.net mvc动作名称,例如www.domain.com/about-us
其中about-us
是家庭控制器中的acton名称。通过这种方法,我可以实现动作名称,如contact-us
,how-to
等。
答案 0 :(得分:9)
您可以在actionName
代码中提供您的操作名称。
[ActionName("about-us")]
public ActionResult AboutUs() {
return View();
}
答案 1 :(得分:6)
由于没有人愿意为问题提供完整的解决方案,这就是在.Net MVC 5项目中如何完成的:
在 RegisterRoute 方法中,修改如下代码:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes(); // <--- add this line to enable custom attribute routes
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
现在,打开您的控制器文件,然后在您的操作顶部添加自定义路线的定义,如下所示:
[Route("about-us")]
public ActionResult AboutUs()
{
return View();
}
您现在应该能够使用这样的自定义路线:
http://yourdomain.com/about-us
答案 2 :(得分:0)
在AreaRegistration.cs
文件中,您可以添加路由表条目,如下所示.....
context.MapRoute(
"about_us_default",
"about-us",
new { action = "AboutUs" }
);
答案 3 :(得分:0)
在MVC5中,您也可以设置属性路由:
[Route("about-us")]
public ActionResult AboutUs()
{
return View();
}