【问题标题】:Error page always loads inside partial view错误页面总是在局部视图中加载
【发布时间】:2017-01-16 15:48:38
【问题描述】:

我一直在努力解决这个问题很长一段时间,但我似乎找不到适合我的解决方案。

我通过覆盖我的 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));
        }

我的错误控制器非常简单:

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

它有效,错误页面显示,但它总是在局部视图容器内加载,即引发错误的局部视图。相反,我只想正确重定向到错误页面。

我尝试过以这种方式使用和处理错误,但它的行为方式完全相同。我也尝试过在 Global.asax Application_Error 方法中处理错误,我知道这不会有任何区别,但我想要 无论如何都要尝试一下..

我的猜测是因为部分视图是通过 $.get 加载的调用它以某种方式将响应包装在部分视图应该加载的同一个 div/容器中。

任何帮助将不胜感激。如果您需要更多信息,请告诉我。

我也尝试在 SO 上查找类似情况,但我发现没有帖子有很好的解决方案...

提前致谢。

【问题讨论】:

    标签: javascript ajax asp.net-mvc error-handling asp.net-ajax


    【解决方案1】:

    您应该做的是,如果错误发生在 ajax 调用中,您应该发送一个带有属性的 json 响应,该属性指示要重定向到哪个 url。如果不是ajax请求,可以发送正常的redirectresult。

    类似的东西

    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"}});
        }
    }
    

    现在您可以监听 .ajaxError() 事件,只要 ajax 请求完成并出现错误,就会触发该事件。获取 RedirectUrl 值并根据需要进行重定向。您还可以考虑向用户显示有意义的消息(即使在模态对话框的部分视图中),这样用户就不会被盲目重定向所迷惑!

    $(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;
            });
    });
    

    【讨论】:

    • 啊$(document).ajaxError!从来没想过。我正在考虑发送 json 作为响应,但只是不确定如何概括所有 ajax 函数的错误处理。我认为这可能只是工作。谢谢,我试试看!
    • 再次感谢您!这就像魅力一样。标记为答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2017-09-01
    • 1970-01-01
    相关资源
    最近更新 更多