简体   繁体   English

错误页面始终在局部视图中加载

[英]Error page always loads inside partial view

I've been struggling to get around this problem for quite a while now but I cannot seem to find a solution that works for me. 我一直在努力解决这个问题很长一段时间但我似乎无法找到适合我的解决方案。

I handle all errors by overriding OnException method in my BaseController class, which all others controllers inherit. 我通过覆盖我的BaseController类中的OnException方法来处理所有错误,所有其他控制器都继承该方法。

protected override void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;
            var rd = new RouteData
            {
                Values = { ["controller"] = "Error", ["action"] = "Index" },
                DataTokens = { }
            };
            var error = $@"Error: {filterContext.Exception.Message} in {filterContext.HttpContext.Request.FilePath}
                           Details: 
                           {filterContext.Exception.StackTrace}";

            _logger = LogManager.GetLogger(GetType());
            _logger.Error(error + Environment.NewLine + "Temp Id: " + AppSession.TempId);

            IController c = new ErrorController();
            c.Execute(new RequestContext(new HttpContextWrapper(System.Web.HttpContext.Current), rd));
        }

My error controller is pretty simple: 我的错误控制器非常简单:

public ActionResult Index()
        {
            ViewBag.Error = "Oops.. Something went wrong";
            return View("Error");
        }

It works, Error page shows up, but it always loads up inside the partial view container, the partial view that raised the error. 它工作,错误页面显示,但它总是在局部视图容器内部加载,部分视图引发错误。 Instead, I want to do a proper redirect to just error page alone. 相反,我想要仅对错误页面进行适当的重定向。

I've tried using and handle errors that way but it behaves in exact same manner. 我尝试过使用和处理错误,但它的行为完全相同。 I've also tried handling errors in Global.asax Application_Error method, which I knew wouldn't make any difference but I wanted to try it anyways.. 我也尝试过在Global.asax Application_Error方法中处理错误,我知道它不会有任何区别,但我还是想尝试一下..

My guess is because the partial view is loaded via $.get call it somehow wraps the response in the same div/container the partial view was supposed to load. 我的猜测是因为部分视图是通过$ .get调用它以某种方式将响应包装在部分视图应该加载的同一个div /容器中。

Any help would be greatly appreciated. 任何帮助将不胜感激。 Should you need more information, please let me know. 如果您需要更多信息,请告诉我。

I've also tried looking up on SO for similar scenarios but no post, that i've found, has a good solution... 我也试过在SO上查找相似的场景但没有帖子,我发现,有一个很好的解决方案......

Thanks in advance. 提前致谢。

What you should be doing is, If the error happens in an ajax call, you should be sending a json response with a property which indicates which url to redirect to. 您应该做的是,如果在ajax调用中发生错误,您应该发送一个带有属性的json响应,该属性指示要重定向到哪个url。 If it is not an ajax request, you can send the normal redirectresult. 如果它不是ajax请求,您可以发送正常的redirectresult。

Something like this 像这样的东西

protected override void OnException(ExceptionContext filterContext)
{
    //your existing code to log errors here

    filterContext.ExceptionHandled = true;
    if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
    {
        var targetUrl = UrlHelper.GenerateUrl("Default", "Index", "Error", 
              new RouteValueDictionary(), RouteTable.Routes, Request.RequestContext, false);

        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            Data = new { Error = true, Message = filterContext.Exception.Message,
                                                                   RedirectUrl= targetUrl }
        };
        filterContext.HttpContext.Response.StatusCode = 500;

        filterContext.ExceptionHandled = true;
    }
    else
    {
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary 
                                          {{"controller", "Error"}, {"action", "Index"}});
    }
}

Now you can listen the .ajaxError() event which will be fired anytime an ajax request completes with an error. 现在,您可以监听.ajaxError()事件,该事件将在ajax请求完成并且出错时触发。 Get the RedirectUrl value and redirect as needed. 获取RedirectUrl值并根据需要重定向。 You may also consider showing a meaningful message to user (Even in a partial view from the modal dialog) so user won't be confused by the blind redirect ! 您还可以考虑向用户显示有意义的消息 (即使在模态对话框的部分视图中),因此用户不会被盲重定向混淆!

$(function () {

        $(document).ajaxError(function (event, request, settings) {           
            console.log('ajax request', request.responseText);
            var d = JSON.parse(request.responseText);
            alert("Ajax error:"+d.Message);
            window.location.href = d.RedirectUrl;
        });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM