Пользовательский обработчик ошибок по-прежнему загружает страницу ошибок по умолчанию

Я соединил обработку ошибок для моего приложения, используя решение в этой публикации. Ссылка. Проблема, которую я получаю, состоит в том, что приложение все еще маршрутизирует к странице ошибки по умолчанию. Код проходит весь путь до Global.asax, когда я ставлю точку останова, но при загрузке пользовательской страницы просмотра ошибок она загружает страницу ошибок по умолчанию из решения. Я попытался удалить страницу ошибки по умолчанию, затем я получил желтую страницу ошибки из IIS. Искал в сети не покладая рук, но безрезультатно. Благодарен за всю помощь. Если вы считаете, что я могу лучше подправить вопрос или название, я открыт для предложений.

Ошибка контроллера:

public class ErrorController : Controller
{
    public ActionResult PageNotFound(Exception ex)
    {
        Response.StatusCode = 404;
        return View("Error", ex);
    }

    public ActionResult ServerError(Exception ex)
    {
        Response.StatusCode = 500;
        return View("Error", ex);
    }

    public ActionResult UnauthorisedRequest(Exception ex)
    {
        Response.StatusCode = 403;
        return View("Error", ex);
    }

    //Any other errors you want to specifically handle here.

    public ActionResult CatchAllUrls()
    {
        //throwing an exception here pushes the error through the Application_Error method for centralised handling/logging
        throw new HttpException(404, "The requested url " + Request.Url.ToString() + " was not found");
    }
}

Код в Global.asax.cs:

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();

        //Error logging omitted

        HttpException httpException = exception as HttpException;
        RouteData routeData = new RouteData();
        IController errorController = new Controllers.ErrorController();
        routeData.Values.Add("controller", "Error");
        routeData.Values.Add("area", "");
        routeData.Values.Add("ex", exception);

        if (httpException != null)
        {
            //this is a basic example of how you can choose to handle your errors based on http status codes.
            switch (httpException.GetHttpCode())
            {
                case 404:
                    Response.Clear();

                    // page not found
                    routeData.Values.Add("action", "PageNotFound");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

                    break;
                case 500:
                    // server error
                    routeData.Values.Add("action", "ServerError");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
                case 403:
                    // server error
                    routeData.Values.Add("action", "UnauthorisedRequest");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
                //add cases for other http errors you want to handle, otherwise HTTP500 will be returned as the default.
                default:
                    // server error
                    routeData.Values.Add("action", "ServerError");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
            }
        }
        //All other exceptions should result in a 500 error as they are issues with unhandled exceptions in the code
        else
        {
            routeData.Values.Add("action", "ServerError");
            Server.ClearError();
            // Call the controller with the route
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
    }

RouteConfig.cs

  routes.MapRoute("CatchAllUrls", "{*url}", new {controller = "Error", action = "CatchAllUrls"});

Блок улова:

throw new HttpException(404, "Unable to write to list" + ", " +  e.InnerException);

1 ответ

С помощью @GeorgPatscheider и @AliAshraf я наконец решил свою проблему. Я заставил ее работать, изменив это возвращаемое представление ("Ошибка", ex.Message); на этот возврат View("Ошибка", ex); и добавил <customErrors mode="On"/>, Теперь я также могу добавить дополнительные коды ошибок HTTP. Я добавил Message в ex после первоначального поста спасибо за помощь!!!

Другие вопросы по тегам