gpt4 book ai didi

c# - MVC中如何使用多个路由

转载 作者:行者123 更新时间:2023-11-30 17:27:02 25 4
gpt4 key购买 nike

我有一个网站需要所有站点的 departmentID,所以我将默认路由重写为以下内容:

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

例如,当您使用以下 URL 时它工作正常:

http://domain/2/Home/Index

或者只是简单地:

http://domain/2

我的问题是当我转到“http://domain/”时出现错误,因为我没有指定 departmentID。我如何添加第二条路由,当您进入域时将触发。

我尝试添加以下内容:

routes.MapRoute(
name: "Start",
url: "/",
defaults: new { controller = "Department", action = "Select"}
);

这是行不通的,因为您不能只将“/”作为 URL。

我还尝试添加默认路由,然后只更改默认对象:

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

这也行不通。

最佳答案

您必须如下修改代码

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

routes.MapRoute(
name: "Department",
url: "{deptID}/{controller}/{action}",
defaults: new { controller = "Department", action = "Index"}
);

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


}

输出

Home URL Department URL with ID

如果以上代码仍然不适合您,请告诉我。

关于c# - MVC中如何使用多个路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55591818/

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