我正在使用 Entity Framework 开发 C# ASP.NET MVC 项目。
我正在尝试使用 RouteConfig.cs
更改 url 路径
首先代码是这样的
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
}
}
我想把 url localhost/Customer/Index
改成 localhost/Index
所以我添加了这行代码并且成功了
routes.MapRoute(
name: "customer",
url: "customer",
defaults: new { controller = "Customer", action = "Index"}
);
接下来,我尝试将 localhost/Customer/Details/2
更改为 localhost/CustomerName/2
。
// CustomerName varies with each customer
所以我加了这个
routes.MapRoute(
name: "customerDetail",
url: "customer/{name}/{id}",
defaults: new { controller = "Customer", action = "Details", id = UrlParameter.Optional, name = UrlParameter.Optional }
);
现在客户详细信息页面可以正确加载。
但是使用此路径加载索引页面 localhost/Customer/Index
会导致错误,而 localhost/Customer
不会导致错误。为什么会这样?
编辑
这就是我的 RouteConfig
的样子
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "customer",
url: "customer",
defaults: new { controller = "Customer", action = "Index"}
);
routes.MapRoute(
name: "customerDetail",
url: "customer/{name}/{id}",
defaults: new { controller = "Customer", action = "Details", id = UrlParameter.Optional, name = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
}
}
最佳答案
终于找到答案了。
As @StephenMuecke commented
localhost/Customer/Index
matches thecustomerDetail
route (and passes"Index"
to the id parameter)
所以我重新检查了我的代码,发现 localhost/Customer/Details/2
中的 id
字段不是可选的,我不小心将它定义为可选的, id = UrlParameter.Optional
.
routes.MapRoute(
name: "customerDetail",
url: "customer/{name}/{id}",
defaults: new { controller = "Customer", action = "Details", name = UrlParameter.Optional }
);
完整的 RoutConfig 代码:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "customer",
url: "customer",
defaults: new { controller = "Customer", action = "Index"}
);
routes.MapRoute(
name: "customerDetail",
url: "customer/{name}/{id}",
defaults: new { controller = "Customer", action = "Details",name = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
}
}
关于c# - 使用 RouteConfig 更改路径后旧路径不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46149574/