1
我在尝试配置ASP.NET MVC项目以将多个URL路由到相同视图时遇到了一些麻烦。鉴于以下网址:将多个URL路由到ASP.NET MVC中的相同视图
localhost:1234
localhost:1234/Products
localhost:1234/Products/1
localhost:1234/Products/abcd
localhost:1234/Products/whatever
我想每一种路由用户在同样的观点(Products.cshtml
,例如)。
继this site一个例子,我饰我的控制器行动,以特殊的路由属性:
[HttpGet]
[Route("Products/{id?}")]
public ActionResult Products(string id)
{
return View();
}
而且在我RouteConfig.cs
文件,我有我的默认路由设置:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Products", action = "Products", id = UrlParameter.Optional }
);
localhost:1234
和localhost:1234/Products
链接都可以工作,但这不适用于其余的URL。
您是否记得在初始化代码中的某处调用MapMvcAttributeRoutes()? –
@MattiVirkkunen哦天啊,不,我没有。这解决了一半的问题,但我称这个功能,默认链接不再起作用。 – alex
您可以在默认路由之前添加其他路由'url:“Products/{id}”,'(具有相同的默认值)并删除'[Route(“Products/{id?}”)]'属性 –