Default route for all extreme situations

独自空忆成欢 提交于 2019-12-11 02:10:49

问题


In my routing I would like to have something like not found route handler.

For example I have created one mapping like

routes.MapRoute(
                     "default",
                     "{controller}/{action}/{id}",
                     new { controller = "Home", action = "Index", id="" }
             );

routes.MapRoute(
                     "Catchall",
                     "{*catchall}",
                     new { controller = "Home", action = "Lost" }
             );

but when user inserts address something like /one/two/three/four/bla/bla it will be cached with the Catchall mapping.

But when user inserts something that should match with default mapping, (like /one/two/ ,but this controller or action is not implemented) I would want that Catchall mapping would accept this request, because all other mappings failed. But instead of this I get an error.

Should I override some mapping handlers to catch the exception if controller or action getting an exception?


回答1:


The issue here is that it's not the Route's responsibility to make sure that "one/two" maps to a file. That responsibility falls to the ViewEngine. Since "one/two" is a valid route, it will be chosen.

If you want to handle the error of an invalid route, what I would recommend you do is simply use the built in ErrorHandling "page" to display whatever message you would have done in the Catchall.




回答2:


I don't think this is the best solution, but you could always be more specific on your routes:

routes.MapRoute(
    "home and action",
    "home/index/{id}",
    new { controller = "Home", action = "Index", id="" }
);

... repeat for the rest of your actions ...

routes.MapRoute(
    "article catch all",
    "home/{article}",
    new { controller = "Home", action = "ArticleSearcher", article="" }
);

This would attempt to match a direct action, and if no action is found, pass what would normally be the {action} part of the default route to the 'ArticleSearcher' action as an article string parameter.

The downside is having to explicitly create each controller/action route.



来源:https://stackoverflow.com/questions/317005/default-route-for-all-extreme-situations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!