gpt4 book ai didi

asp.net-mvc - 在 MVC 5 中添加路由

转载 作者:行者123 更新时间:2023-12-02 04:17:06 26 4
gpt4 key购买 nike

我有一个要求,我必须映射以下网址

/amer/us/en/ = Home controller
/amer/us/en/login/index = Home controller
/amer/us/en/confirmation = Confirmation controller

以及常规的默认操作。

例如,如果用户前往

http:\\test.com --> http://test/home/index
http:\\test.com/amer/us/en/login/index --> http://test/home/index
http:\\test.com/amer/us/en/ --> http://test/home/index

我正在研究属性路由,因此我在 HomeController 中添加了以下代码

  [RoutePrefix("amer/us/en/")]
[Route("{action=index}")]
public class HomeController : Controller
{

}

我收到此错误名为“Home”的 Controller 上的路由前缀“amer/us/en/”不能以正斜杠开头或结尾并且默认路由现在无法工作,因此 http://test.com没有加载任何东西。下面是我的默认 RouteConfig 类。

 public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapMvcAttributeRoutes();

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

对 MVC 非常陌生。有人可以告诉我我在这里做错了什么吗?

最佳答案

MVC 中的路由可以通过在 RouteConfig 类中定义路由或通过属性路由(或者您可以使用区域)来工作。使用 RouteConfig 进行路由按照您定义路由的顺序进行。当请求到来时,MVC 会从上到下尝试你的路由,并执行第一个与请求的 url 匹配的路由。因此,您示例中的路由需求可以通过以下方式实现:

routes.MapRoute(
name: "RootLogin",
url: "amer/us/en/login/index/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
name: "DefaultAmer",
url: "amer/us/en/{controller}/{action}{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

这会将登录映射为特殊路由,所有其他 /amer/us/en/ 路由将转到随后发生的任何 controller 以及任何 action 它。最后一个路由,如果请求不是以 /amer/us/en 开头,将执行默认行为。

但是,您似乎想要将 /amer/us/en/ 定义为一个区域,因此您可能也想看看它。

关于asp.net-mvc - 在 MVC 5 中添加路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33045029/

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