gpt4 book ai didi

asp.net-mvc - 如果抛出自定义异常,则重定向asp.net mvc

转载 作者:行者123 更新时间:2023-12-04 07:13:58 24 4
gpt4 key购买 nike

如果我的应用程序中引发了自定义错误,我需要全局重定向我的用户。我尝试将一些逻辑放入我的global.asax文件中以搜索我的自定义错误,如果引发了该错误,请执行重定向,但是我的应用程序从未命中我的global.asax方法。它一直给我一个错误,指出我的异常未由用户代码处理。

这就是我在全局范围内拥有的东西。

protected void Application_Error(object sender, EventArgs e)
{
if (HttpContext.Current != null)
{
Exception ex = HttpContext.Current.Server.GetLastError();
if (ex is MyCustomException)
{
// do stuff
}
}
}

而我的异常抛出如下:
if(false)
throw new MyCustomException("Test from here");

当我从引发异常的文件中将其放入try catch中时,我的Application_Error方法永远无法到达。有人对我如何在全局范围内处理此问题有任何建议(使用我的自定义异常处理)?

谢谢。

1/15/2010编辑:
这是//做事的内容。
RequestContext rc = new RequestContext(filterContext.HttpContext, filterContext.RouteData);
string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "Home", action = "Index" })).VirtualPath;
filterContext.HttpContext.Response.Redirect(url, true);

最佳答案

您要为 Controller /操作创建客户过滤器。您需要从FilterAttributeIExceptionFilter继承。

像这样的东西:

public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception.GetType() == typeof(MyCustomException))
{
//Do stuff
//You'll probably want to change the
//value of 'filterContext.Result'
filterContext.ExceptionHandled = true;
}
}
}

一旦创建了它,就可以将该属性应用于所有其他 Controller 都继承自的BaseController,以使其具有站点范围的功能。

这两篇文章可能会有所帮助:
  • Filters in ASP.NET MVC - Phil Haack
  • Understanding Action Filters
  • 关于asp.net-mvc - 如果抛出自定义异常,则重定向asp.net mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2067351/

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