如何在c#中的某些路由上抛出自定义错误

时间:2018-06-08 14:26:00

标签: c# asp.net-mvc asp.net-mvc-routing custom-errors

如果我执行类似

的操作,我会收到自定义错误
https://localhost:xxxx/TryStuff  

但如果我做的话

https://localhost:xxxx/AbcController/Details/1234/TryStuff

它不会抛出自定义错误。它会抛出类似

的东西

enter image description here

路线档案:

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


routes.MapRoute(
    name: "Error",
    url: "{controller}/{action}/{id}",
    defaults: new
    {
        controller = "Error",
        action = "NotFound",
        id = UrlParameter.Optional
    });

1 个答案:

答案 0 :(得分:2)

你需要捕获所有路线

//Catch-All InValid (NotFound) Routes
routes.MapRoute(
    name: "NotFound",
    url: "{*url}",
    defaults: new { controller = "Error", action = "NotFound" }
);

在所有其他路线之后添加此路线。

之前未捕获的任何路线都将匹配此路线并路由到相应的控制器。