gpt4 book ai didi

c# - 如何用连字符实现 asp.net mvc Action 名称?

转载 作者:太空狗 更新时间:2023-10-29 20:54:43 25 4
gpt4 key购买 nike

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

最佳答案

这是 .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. 现在,打开您的 Controller 文件,然后在您的操作顶部添加自定义路由的定义,如下所示:

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

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

http://yourdomain.com/about-us

关于c# - 如何用连字符实现 asp.net mvc Action 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com