我试图在我的 MVC 应用程序中“捕获所有”500 和 404 错误,但我似乎无法掌握需要什么,即使在阅读了所有文章和问题之后也是如此。
Web.config
(这允许 500 错误去~/Views/Shared/Error.cshtml
):
<system.web>
<customErrors mode="On" redirectMode="ResponseRewrite" />
</system.web>
我已经设置了HomeController
抛出错误来测试上述设置:
public ActionResult Index()
{
//Testing errors
throw new Exception("Exception");
return View();
}
在我的Global.asax.cs
中,我有以下记录 500 错误:
protected void Application_Error()
{
var ex = Server.GetLastError();
//Custom ExceptionLog
new ExceptionLogHelper().Add("Application_Error", Response.Status, ex);
}
现在对于 404 错误:
在我的RouteConfig.cs
中,我有以下路线,但似乎无法捕获所有 404:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Error",
url: "Error/{code}",
defaults: new { controller = "Error", action = "Index", code = UrlParameter.Optional }
);
//routes.MapRoute(
// name: "Controllers",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Error", action = "Index", code = UrlParameter.Optional }
//);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
//Keep at bottom
routes.MapRoute("CatchAll", "{*url}", new { controller = "Error", action = "Index", name = "no-route-found", code = "404" });
}
}
CatchAll
在底部做得很好,可以捕捉到与前面的路线不匹配的所有东西。
我有很多测试场景,但困扰我的是以下 UrlParameter:
http://localhost:64275/does/not/exist/
上面的网址本质上是http://localhost:64275/{controller}/{action}/{id}
我没有一个名为 的控制器does
,我认为如果没有匹配的控制器,它defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
会默认为Home
具有 Action 的控制器。Index
另一个有效的例子:
http://localhost:64275/a/a/a/a/ (because it has 4 parts, not 3 or less)
有人可以解释我可能会出错的地方吗?......我不明白什么?
我是否应该实现这样的东西:.Net MVC Routing Catchall not working (Darin Dimitrov's answer)
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "HttpError500");
if (httpException.GetHttpCode() == 404)
{
routeData.Values["action"] = "HttpError404";
}
Server.ClearError();
Response.Clear();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
}