asp.net mvc中在Filter中跳转千万不要使用Response.Redirect

查看原文

如题,如果在Filter中用Response.Redirect,虽然URL是跳转了,但是之后的Filter和Action还是会执行,不仅浪费资源,还会产生一些不必要的错误,或许,这些错误仅在你的错误日志中能看到。

在Filter中错误使用跳转如下:

[c-sharp] view plaincopy

public class AnchorFilter : ActionFilterAttribute  

    {  

        public override void OnActionExecuting(ActionExecutingContext filterContext)  

        {  

                if (!string.IsNullOrEmpty(filterContext.HttpContext.Request.QueryString["r_Anchor"]))  

                {  

                    filterContext.HttpContext.Response.Redirect(string.Format("{0}#{1}",  

                                                                              filterContext.HttpContext.Request.Url.  

                                                                                  AbsolutePath,  

                                                                              filterContext.HttpContext.Request.  

                                                                                  QueryString["r_Anchor"]));  

                    return;  

                }  

           

             

            base.OnActionExecuting(filterContext);  

        }  

    }  

使用filterContext.HttpContext.Response.Redirect 就会产生后遗症,正确使用应该是:

public class AnchorFilter : ActionFilterAttribute  

    {  

        public override void OnActionExecuting(ActionExecutingContext filterContext)  

        {  

                if (!string.IsNullOrEmpty(filterContext.HttpContext.Request.QueryString["r_Anchor"]))  

                {  

                    filterContext.Result = new RedirectResult(string.Format("{0}#{1}",  

                                                                              filterContext.HttpContext.Request.Url.  

                                                                                  AbsolutePath,  

                                                                              filterContext.HttpContext.Request.  

                                                                                  QueryString["r_Anchor"]));  

                    //filterContext.HttpContext.Response.Redirect(string.Format("{0}#{1}",  

                    //                                                          filterContext.HttpContext.Request.Url.  

                    //                                                              AbsolutePath,  

                    //                                                          filterContext.HttpContext.Request.  

                    //                                                              QueryString["r_Anchor"]));  

                    return;  

                }  

             

             

            base.OnActionExecuting(filterContext);  

        }  

    }  

你可能感兴趣的:(response)