加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 04:29:39 所属栏目:asp.Net 来源:网络整理
导读:如果在我的应用程序中抛出自定义错误,我需要全局重定向我的用户.我已经尝试将一些逻辑放入我的global.asax文件中以搜索我的自定义错误,如果它被抛出,执行重定向,但我的应用程序永远不会访问我的global.asax方法.它一直给我一个错误,说我的异常未被用户代码处
如果在我的应用程序中抛出自定义错误,我需要全局重定向我的用户.我已经尝试将一些逻辑放入我的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方法永远不会到达.任何人都有一些关于如何全局处理这个问题的建议(处理我的自定义异常)?

谢谢.

2010年1月15日编辑:
这是//做什么的东西.

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

解决方法

您想为控制器/操作创建客户过滤器.您需要继承FilterAttribute和IExceptionFilter.

像这样的东西:

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

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

这两篇文章可以帮助:

> Filters in ASP.NET MVC – Phil Haack
> Understanding Action Filters

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读