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

Kyl*_*yle 8 asp.net-mvc redirect exception-handling

如果在我的应用程序中抛出自定义错误,我需要全局重定向我的用户.我已经尝试将一些逻辑放入我的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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的异常抛出如下:

if(false)
    throw new MyCustomException("Test from here");
Run Code Online (Sandbox Code Playgroud)

当我把它放入抛出异常的文件中的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);
Run Code Online (Sandbox Code Playgroud)

Cha*_*ino 10

您想为控制器/操作创建客户过滤器.你需要继承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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

这两篇文章可以帮助: