Mvc Filter中的Redirect

      在Mvc中有ExceptionFilter,当对controller或者action定义ExceptionFilter后,在执行方法抛出异常时,能在ExceptionFilter里面进行逻辑处理,当设置Exception-Handled为true后,异常将不会向上继续传递。但是有一种比较意外的情况,当在Filter里面实现重定向时,会抛出一个ThreadAbortException,那抛出的这个异常是不是也会被ExceptionFilter捕获进行处理,设置ExceptionHandled为true后,从而不能实现正确的跳转。如果通过测试可以发现在Filter里面实现重定向还是可以跳转成功的。在Mvc的源码里面InvokeActionMethodFilter有这么一段话。可以发现对于ThreadAbortException Mvc框架是做了一个特殊的处理。

View Code
1 try {
2 postContext = continuation();
3 }
4 catch (ThreadAbortException) {
5 // This type of exception occurs as a result of Response.Redirect(), but we special-case so that
6 // the filters don't see this as an error.
7   postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, null /* exception */);
8 filter.OnActionExecuted(postContext);
9 throw;
10 }
11 catch (Exception ex) {
12 wasError = true;
13 postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, ex);
14 filter.OnActionExecuted(postContext);
15 if (!postContext.ExceptionHandled) {
16 throw; //注意这里
17   }
18 }
19 if (!wasError) {
20 filter.OnActionExecuted(postContext);
21 }
posted @ 2011-04-28 09:24  雁北飞  阅读(1251)  评论(0编辑  收藏  举报