gpt4 book ai didi

asp.net-mvc - 将 Index 设置为 Controller 的默认路由

转载 作者:行者123 更新时间:2023-12-04 07:29:44 25 4
gpt4 key购买 nike

我有一个网址

  • http://www.roadkillwiki.org/Page/Index/documentation

  • 我想变成
  • http://www.roadkillwiki.org/Page/documentation

  • 这也可能类似于 http://www.roadkillwiki.org/Page/my-url-with-spaces - 参数是一个字符串。我试过的路线设置是:
    routes.MapRoute(
    "ControllerDefault",
    "{controller}/{id}",
    new { controller = "Page", action = "Index", id = UrlParameter.Optional }
    );

    但是,这会干扰 MVC 项目附带的默认“id”路由。有没有办法实现这一目标?

    最佳答案

    您不需要丢失默认路由。避免您的路线相互干扰的关键是对它们进行排序,以便更具体的规则先于不太具体的规则。例如:

    // Your specialized route
    routes.MapRoute(
    "Page",
    "Page/{slug}",
    new { controller = "Page", action = "Index" }
    );

    // Default MVC route (fallback)
    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

    然后你的 PageController 看起来像这样:
    using System.Web.Mvc;

    public class PageController : Controller
    {
    public string Index(string slug)
    {
    // find page by slug
    }
    }

    也就是说,我会 强烈建议您改为这样做:
    // Your specialized route
    routes.MapRoute(
    "Page",
    "Page/{id}/{slug}",
    new { controller = "Page", action = "Index", slug = UrlParameter.Optional }
    );

    // MVC's default route (fallback)
    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

    还有你的 PageController:
    using System.Web.Mvc;

    public class PageController : Controller
    {
    public string Index(int id)
    {
    // find page by ID
    }
    }

    通过在 URL 的开头(如 StackOverflow 所做的)或末尾包含页面 ID,您可以忽略该 slug,而是通过 ID 检索您的页面。如果您的用户更改页面名称,这将为您省去很多麻烦。我经历了这一切,这很痛苦;您基本上必须记录您的页面过去的所有名称,这样您的访问者/搜索引擎就不会在每次重命名页面时收到 404。

    希望这可以帮助。

    关于asp.net-mvc - 将 Index 设置为 Controller 的默认路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5252925/

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