Как отобразить представление, когда вы находитесь в обработчике события Application_Error, не перенаправляя пользователя? - PullRequest
0 голосов
/ 30 сентября 2019

Предположим, что ваше приложение вызвало исключение, которое не входит в область действия метода ControllerActionInvoker.InvokeAction.

Это может произойти, например, если пользователь ввел неправильный URLкоторое не разрешается до имени какого-либо существующего контроллера или действия.

http://www.example.com/doesNotExist

Этот URL будет выдавать HttpException с кодом состояния 404.

Затем вы можете обработать это вобработчик событий Application объекта Error.

// Global.asax.cs
public void Application_Error()
{
  HttpException exception = Server.GetLastError() as HttpException;

  // do whatever with it
}

С этого момента возможно отображение ASP.NET MVC View без фактического перенаправления пользователя на новый URL, который будет отображать представление ?

// Global.asax.cs
public void Application_Error()
{
  HttpException exception = Server.GetLastError() as HttpException;

  // can I *render* a View here?
  // In other words, can I execute a ViewResult here?
  // Can I get back into MVC from here?
  // But without redirecting the user. Just re-writing the Response object?
}

Все примеры, которые я видел здесь, просто устанавливают HTTP StatusCode и StatusDescription на Response объект. Я хотел бы вернуться к View отсюда без перенаправления пользователя на URL-адрес просмотра .

Я использую ASP.NET MVC 5.2.6 для таргетинга на .NET Framework 4.60,1.

1 Ответ

0 голосов
/ 05 октября 2019

Чего вы пытаетесь достичь, но не перенаправляете пользователя на страницу с ошибкой?

Наша собственная реализация Application_Error() перехватывает и регистрирует ошибку в нашей базе данных перед выполнением метода нашей ошибкиконтроллер, но это, по сути, просто перенаправляет пользователя на дружественную страницу, где мы показываем ему соответствующую информацию об ошибке, чтобы они могли сообщить о ней, например;

Global.aspx.cs

    protected void Application_Error()
    {
        string showerrors = ConfigurationManager.AppSettings["ShowErrors"];
        string appid = ConfigurationManager.AppSettings["ApplicationId"];

        if (showerrors != "Y")
        {
            Exception ex = Server.GetLastError();
            var httpex = ex as HttpException;

            if (HttpContext.Current != null)
            {
                Response.Clear();
            }
            Server.ClearError();

            if (ex is HttpException && ex.InnerException is ViewStateException)
            {
                Response.Redirect(Request.Url.AbsoluteUri);
                return;
            }

            ApplicationError err = new ApplicationError();

            err.ApplicationId = appid;
            err.ErrorCode = httpex == null ? 0 : httpex.GetHttpCode();
            err.ErrorMessage = ex.Message;

            err.UserId = User != null ? User.Identity.Name : null;
            err.IPAddress = Request.ServerVariables["REMOTE_HOST"];
            err.Referrer = Request.ServerVariables["HTTP_REFERER"];
            err.Url = Request.Url.ToString();
            err.StackTrace = ex.StackTrace;

            string[] errorstoignore = new string[] { "__VIEWSTATE", "PASSWORD" };

            StringBuilder sbfv = new StringBuilder();
            foreach (string s in Request.Form.AllKeys)
            {
                if (!errorstoignore.Contains(s.ToUpper()))
                {
                    if (sbfv.Length > 0)
                    {
                        sbfv.Append(", ");
                    }
                    if (!s.ToLower().Contains("password"))
                    {
                        sbfv.Append(s + ":" + Request.Form[s] + "\n");
                    }
                    else
                    {
                        sbfv.Append(s + ":********" + "\n");
                    }
                }
            }
            err.FormValues = sbfv.ToString();
            err.ErrorDate = DateTime.Now;

            ApplicationServices asvcs = new ApplicationServices();
            asvcs.AddError(err);

            var routeData = new RouteData();
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = "Index";
            routeData.Values["id"] = err.ErrorId;
            routeData.Values["exception"] = ex;

            IController errorsController = new ErrorController();
            var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
            errorsController.Execute(rc);
        }
    }

ErrorController.cs

    [AllowAnonymous]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    [NoAntiForgeryCheck]
    public ActionResult Index(int id, Exception exception)
    {
        string errortitle = "Application Error";
        int errid = (exception is HttpException) ? ((HttpException)exception).GetHttpCode() : 0;
        string msg = exception.Message;

        switch (errid)
        {
            case 0:
                errortitle = "Internal Application Error";
                msg = "See error log or debug";
                break;
            case 400:
                //Bad Request
                errortitle = "Security Violation";
                msg = "The page could not be opened.";
                break;
            case 401:
                //Unauthorized
                errortitle = "Security Violation";
                msg = "The page could not be opened.";
                break;
            case 402:
                //Payment Required
                errortitle = "Payment Required";
                break;
            case 403:
                //Forbidden
                errortitle = "Security Violation";
                msg = "The page could not be opened.";
                break;
            case 404:
                //Not Found
                errortitle = "Navigation Error";
                msg = "The page could not be opened.";
                break;
            case 405:
                //Method Not Allowed
                errortitle = "Security Violation";
                msg = "The page could not be opened.";
                break;
            case 406:
                //Not Acceptable
                errortitle = "Not Acceptable";
                break;
            case 500:
                //Internal Server Error
                errortitle = "Internal Server Error";
                if (exception is HttpAntiForgeryException)
                {
                    errortitle = "Security Violation";
                }
                break;
            case 501:
                //Not Implemented
                errortitle = "Not Implemented";
                break;
            case 502:
                //Bad Gateway
                errortitle = "Bad Gateway";
                break;
        }
        //Generate an error reference
        string appid = ConfigurationManager.AppSettings["ApplicationId"];
        string errorref = appid + id.ToString("00000");
        ViewBag.Id = id;
        ViewBag.ErrorTitle = errortitle;
        ViewBag.ErrorMessage = msg;
        ViewBag.IsFullPage = "N";
        ViewBag.ErrorAction = "Please contact your Technical Support Desk quoting reference " + errorref + " to report this error.";
        //ViewBag.ReturnUrl = Request.UrlReferrer == null ? String.Empty : Request.UrlReferrer.AbsoluteUri.ToString();

        return PartialView();
    }

Если вам это не поможет, я не уверен, пока не пойму, что вы пытаетесь сделать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...