在我的MVC Web项目。我试图显示自定义错误页,我的客人不使用“custromerrors”元素在web.config中。

我可以捕捉异常像以下

protected void Application_Error(object sender, EventArgs e)
{

    Exception exception = Server.GetLastError();

    bool success = RaiseErrorSignal(exception);

    Response.Clear();

    HttpException httpException = exception as HttpException;

    RouteData routeData = new RouteData();
    routeData.Values.Add("controller", "Error");

    if (httpException == null)
    {
        routeData.Values.Add("action", "Index");
    }
    else //It's an Http Exception, Let's handle it.
    {
        switch (httpException.GetHttpCode())
        {
            case 404:
                // Page not found.
                routeData.Values.Add("action", "Error404");
                break;
            case 500:
                // Server error.
                routeData.Values.Add("action", "Error500");
                break;

            // Here you can handle Views to other error codes.
            // I choose a General error template  
            default:
                routeData.Values.Add("action", "Index");
                break;
        }
    }

    // Pass exception details to the target error View.
    routeData.Values.Add("error", exception);

    // Clear the error on server.
    Server.ClearError();

    // Call target Controller and pass the routeData.
    IController errorController = new ProjectName.WebSite.Controllers.ErrorController();
    errorController.Execute(new RequestContext(
         new HttpContextWrapper(Context), routeData));


}

private static bool RaiseErrorSignal(Exception e)
{
    var context = HttpContext.Current;
    if (context == null)
        return false;
    var signal = ErrorSignal.FromContext(context);
    if (signal == null)
        return false;
    signal.Raise(e, context);
    return true;
}

但是ELMAH不能记录错误也我提出误差信号。

有帮助吗?

解决方案

我发现这个问题,我错过一个web.config部分。我添加 “错误日志” 模块<system.webserver><modules>

我还需要将其添加到<system.web><httpModules>

添加后,ELMAH开始记录错误。

此外,我不需要调用ErrorSignal.Raise()方法,可以ELMAH检测错误无需信令。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top