如何使用连字符实现asp.net mvc动作名称?

时间:2013-09-03 07:44:23

标签: c# asp.net-mvc asp.net-mvc-routing

如何用连字符实现asp.net mvc动作名称,例如www.domain.com/about-us其中about-us是家庭控制器中的acton名称。通过这种方法,我可以实现动作名称,如contact-ushow-to等。

4 个答案:

答案 0 :(得分:9)

您可以在actionName代码中提供您的操作名称。

[ActionName("about-us")]
public ActionResult AboutUs() {
    return View();
}

答案 1 :(得分:6)

由于没有人愿意为问题提供完整的解决方案,这就是在.Net MVC 5项目中如何完成的:

  1. 打开项目的 App_Start / RouteConfig.cs 文件。
  2. 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 }
        );
    }
    
  3. 现在,打开您的控制器文件,然后在您的操作顶部添加自定义路线的定义,如下所示:

    [Route("about-us")]
    public ActionResult AboutUs()
    {
        return View();
    }
    
  4. 您现在应该能够使用这样的自定义路线:

    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();
    }