控制器不存在时不传递应用程序错误



我想在全局中使用Application_Error()。asax记录网站上的坏URL并重定向到自定义错误登陆页面。问题是为什么当控制器不存在时,网站不能通过应用程序错误。

我测试了下面的URL和所有通过应用程序错误:

  • http://localhost: 11843/账户/randomtext
  • http://localhost: 11843/Home/randomtext randomval

这个不通过应用程序错误,返回404:

  • http://localhost: 11843/nonExistingController

应用程序错误码:

protected void Application_Error(object sender, EventArgs e)
{
     var requestTime = DateTime.Now;
     Exception ex = Server.GetLastError().GetBaseException();
     //log Request.Url.ToString()
}

RouteConfig.cs代码:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
    name: "Account",
    url: "Account/{action}/{id}",
    defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
    name: "Home",
    url: "Home/{action}/{test}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
    name: "HomeBlank",
    url: "",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

请在您的RouteConfig.cs中添加以下内容:

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

一些url将无法被解析,添加以上将处理这些情况。在ErrorControllerNotFound操作中,您可以向用户显示您的自定义错误页面。

public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View();
    }
}

相关内容

最新更新