gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 和 Ajax 中的异常处理 - [HandleException] 过滤器

转载 作者:行者123 更新时间:2023-12-01 19:33:52 26 4
gpt4 key购买 nike

全部,

我正在学习 MVC 并将其用于业务应用程序 (MVC 1.0)。

我真的很难理解异常处理。我在网上花了很多时间,但没有找到任何符合我要求的内容。

我们当前使用实现 IExceptionFilter 的过滤器属性。我们用它来装饰一个基本 Controller 类,以便所有服务器端异常都很好地路由到显示错误并执行日志记录的异常页面。

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

是否有任何方法可以强制在服务器上进行重定向(例如 ASP.NET Server.Transfer 或重定向?)

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

有谁能举个简单的例子(.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,
};
}
}

最佳答案

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

关于asp.net-mvc - ASP.NET MVC 和 Ajax 中的异常处理 - [HandleException] 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2572578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com