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

Raj*_* MG 6 c# asp.net-mvc asp.net-mvc-routing

如何实现asp.net的MVC动作名称连字符例如,www.domain.com/about-us这里about-us是在家庭控制器阿克顿名.通过这种方法,我可以实现有动作名称一样contact-us,how-to

jai*_*444 8

您可以在actionName标记内提供操作名称.

[ActionName("about-us")]
public ActionResult AboutUs() {
    return View();
}
Run Code Online (Sandbox Code Playgroud)


Jho*_*lla 8

由于没有人愿意为问题提供完整的工作解决方案,因此在.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 }
        );
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 现在,打开您的控制器文件,然后在您的操作顶部添加自定义路线的定义,如下所示:

    [Route("about-us")]
    public ActionResult AboutUs()
    {
        return View();
    }
    
    Run Code Online (Sandbox Code Playgroud)

您现在应该能够使用这样的自定义路线:

http://yourdomain.com/about-us
Run Code Online (Sandbox Code Playgroud)