代码之家  ›  专栏  ›  技术社区  ›  GrahamB

asp.net mvc和ajax中的异常处理-[handleexception]过滤器

  •  7
  • GrahamB  · 技术社区  · 15 年前

    所有的,

    我正在学习MVC并将其用于商业应用程序(MVC1.0)。

    我真的很难理解异常处理。我在网上花了很多时间,但没有发现任何与我所追求的一致的东西。

    我们当前使用实现iexceptionfilter的filter属性。我们用这个来修饰一个基本控制器类,以便所有服务器端异常都被很好地路由到一个异常页,该页显示错误并执行日志记录。

    我已经开始使用返回json数据的ajax调用,但是当服务器端实现抛出错误时,会触发过滤器,但页面不会重定向到错误页面-它只是停留在调用ajax方法的页面上。

    是否有任何方法强制服务器上的重定向(例如,asp.net服务器。传输或重定向?)

    我读过我 必须 返回一个JSON对象(包装.NET异常),然后在客户端上重定向,但是我不能保证客户端会重定向…但随后(虽然我可能做错了什么),服务器尝试重定向,但却得到了一个未经授权的异常(基本控制器是安全的,但异常控制器不是因为它不是从这个继承的)

    有人请举个简单的例子(.net和jquery代码)。我觉得我在随意尝试,希望能成功

    到目前为止,异常筛选器…

    public class HandleExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        #region IExceptionFilter Members
    
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)
            {
                return;
            }
    
            filterContext.Controller.TempData[CommonLookup.ExceptionObject] = filterContext.Exception;
    
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = AjaxException(filterContext.Exception.Message, filterContext);
            }
            else
            {
                //Redirect to global handler
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = AvailableControllers.Exception, action = AvailableActions.HandleException }));
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
            }
        }
    
        #endregion
    
        private JsonResult AjaxException(string message, ExceptionContext filterContext)
        {
            if (string.IsNullOrEmpty(message))
            {
                message = "Server error";   //TODO: Replace with better message
            }
    
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;       //Needed for IIS7.0
    
            return new JsonResult
            {
                Data = new { ErrorMessage = message },
                ContentEncoding = Encoding.UTF8,
            };
        }
    }
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   Dave Swersky    15 年前

    我用了失败的肩膀 Ajax.Beginform ()客户端故障处理程序可以通过设置window.location(在许多其他选项中)来重定向。这将在99%的现代浏览器中工作-如果浏览器支持ajax,它应该支持这一点。