我正在尝试在 Asp.Net MVC 应用程序中使用路由约束。
routes.MapRoute(
"theRoute",
"MyAction/{page}",
new { controller = "TheController", action = "MyAction", page = 1 },
new { page = @"[0-9]" });
当我输入像 ~/MyAction/aString 这样的 url 时,会显示 YSOD 并显示无效操作异常。如何将无效网址重定向到 404 页面?
我知道我可以通过 Controller 操作中的字符串参数和 int.TryParse 来解决问题,但是路由约束就没用了。
如何选择路由约束抛出的异常类型?
最佳答案
问题是您没有与以字符串结尾的路由相匹配的路由。
修改您的路线,类似于:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = 0 },
new { id = "[0-9]" }// Parameter defaults
);
routes.MapRoute(
"Default2", // Route name
"{controller}/{action2}/{sid}", // URL with parameters
new { controller = "Home", action = "Index2", sid = "" } // Parameter defaults
);
并修改你的 Controller
public ActionResult Index(int id)
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC! Your id is: "+ id.ToString();
return View();
}
public ActionResult Index2(string sid)
{
ViewData["Title"] = "Home Page 2."+sid.ToString();
ViewData["Message"] = "Welcome to ASP.NET MVC! \"" + sid.ToString() +"\" is an invalid id";
return View("index");
}
现在,当您传递 ID 的字符串时,将调用 Index2,您可以执行任何您需要执行的操作来处理不正确的参数。
关于asp.net-mvc - Asp.Net Mvc 路由约束可以抛出 404 而不是 InvalidOperationException 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/314558/