如何使用HandleErrorAttribute从.net mvc3全局过滤器中记录404错误?

Aca*_*uza 1 asp.net asp.net-mvc log4net asp.net-mvc-3

我正在尝试从HandleErrorAttribute中从我的派生类中记录404 错误.

这是我的班级:

public class LogExceptionAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext exceptionContext)
    {
        Log.LogException(exceptionContext.Exception, exceptionContext.Exception.Message);
        base.OnException(exceptionContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在应用程序中得到所有异常,但我没有得到404错误.我想得到各种错误,例外.

Ric*_*ard 5

您将需要一个最后注册的catchall路由,然后在控制器记录错误后以404响应:

 routes.MapRoute(
                                "NotFound", 
                                "{*url}", 
                               new {controller = "NotFound", action = "index"}
                               )


public class NotFoundController: Controller 
{
    public ActionResult Index(string url)
    {
            Log.Warn(this, string.Format("404 Request Not Found: {0}", url));
            Response.StatusCode = 404;
            var model = new NotFoundViewModel
                            {
                                Title = "Sorry but the page you are looking for does not exist",
                                Message = new HtmlString("Please <a href='/'>click here</a> to return to the home page")
                            };

            return View("404", model);
     }

}
Run Code Online (Sandbox Code Playgroud)