我在尝试让路由与 ASP.NET MVC 3.0 一起工作时遇到问题。我声明了以下路线:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "RsvpForm", id = UrlParameter.Optional }
);
routes.MapRoute(
"TestRoute",
"{id}",
new { controller = "Product", action = "Index3", id = UrlParameter.Optional }
);
routes.MapRoute(
"TestRoute2",
"{action}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
当我访问时:
http://localhost
该站点正常运行,并且似乎命中了 Default
路由。
当我访问时:
http://localhost/1
我得到一个 404:
Server Error in '/' Application.
The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /1
以下是这些路由对应的操作:
public ActionResult Index3(int? id)
{
Product myProduct = new Product
{
ProductID = 1,
Name = "Product 1 - Index 3",
Description = "A boat for one person",
Category = "Watersports",
Price = 275M
};
Product myProduct2 = new Product
{
ProductID = 2,
Name = "Product 2 - Index 3",
Description = "A boat for one person",
Category = "Watersports",
Price = 275M
};
ViewBag.ProcessingTime = DateTime.Now.ToShortTimeString();
if (id == 1)
return View("index", myProduct);
else
return View("index", myProduct2);
}
如何构建我的路线,以便正确命中所有三种操作方法?
最佳答案
ASP.NET MVC 路由从上到下评估路由。因此,如果两条路线匹配,它命中的第一个路线(靠近 RegisterRoutes
方法的“顶部”的路线)将优先于后续路线。
考虑到这一点,您需要做两件事来解决您的问题:
- 您的默认路线应该在底部。
- 如果它们包含相同数量的段,则您的路线需要对其进行约束:
有什么区别:
example.com/1
和
example.com/index
对于解析器,它们包含相同数量的段,并且没有区分符,因此它将命中列表中匹配的第一个路由。
要解决这个问题,您应该确保使用 ProductIds
的路由采用约束:
routes.MapRoute(
"TestRoute",
"{id}",
new { controller = "Product", action = "Index3", id = UrlParameter.Optional },
new { id = @"\d+" } //one or more digits only, no alphabetical characters
);
您的设置还有其他问题,但我马上想到了这两件事。
关于c# - 如何使用 ASP.NET MVC 中的路由修复 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8737535/