如何处理 MVC 中不存在的路由导致错误?

发布于 2024-08-04 06:33:46 字数 1096 浏览 10 评论 0原文

在我的应用程序中,我有一些使用特定路由的控制器和一些使用默认路由的控制器。结果,我有这样的结果:

//.. other more specific routes
routes.MapRoute(
                "Workout - Specific Workouts by exercise",
                "{userName}/workouts/exercise/{exerciseID}/{exerciseName}",
                new { controller = "Workout", action = "WorkoutsByExercise" }
                );

            routes.MapRoute(
                "Default",                                             
                "{controller}/{action}/{id}",                           
                new { controller = "Home", action = "Index", id = "" } 
            );
            routes.MapRoute(
                "Error",
                "{*catchall}",
                new { controller = "Error", action = "Http404" }
 );

但是,如果我输入类似 ~/Home/SomethingThatDoesntExist 的内容,它将被默认路由器拾取,因此永远不会到达我的包罗万象的路由处理程序。我已经通过 Phil Haack 的路由调试器验证了这一点。结果,它将尝试到达该控制器/操作,但找不到它。作为回报,StructureMap 抛出一个错误,该错误上升到 Application_Error ,我无法重定向它(尽管我已经尝试并通过研究进行了一切)。

那么,是否有解决这个问题的方法,或者我是否必须为我的所有控制器和操作指定特定的路由,以及一旦我处于 Application_Error() 状态,如何重定向到特定的页面/控制器?

In my application, I have some controllers that use specific routes and some that use the default route. As a result, I have something like this:

//.. other more specific routes
routes.MapRoute(
                "Workout - Specific Workouts by exercise",
                "{userName}/workouts/exercise/{exerciseID}/{exerciseName}",
                new { controller = "Workout", action = "WorkoutsByExercise" }
                );

            routes.MapRoute(
                "Default",                                             
                "{controller}/{action}/{id}",                           
                new { controller = "Home", action = "Index", id = "" } 
            );
            routes.MapRoute(
                "Error",
                "{*catchall}",
                new { controller = "Error", action = "Http404" }
 );

However, if I type something like ~/Home/SomethingThatDoesntExist it will be picked up by the default router and thus never gets to my catchall route handler. I've verified this through Phil Haack's route debugger. As a result, it will try to get to that controller/action and wont find it. In return, StructureMap throws an error which bubbles up to Application_Error where I can't redirect it (despite everything I've tried and through research).

So, is there anyway around this or do I have to specify specific routes for all of my controllers and actions AND how can I redirect to a specific page/controller once I'm in Application_Error()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文