關於錯誤”服務器無法在已發送 HTTP 標頭之后設置狀。“


最近在做權限時候,直接在AuthorizeCore中寫了httpContext.Response.Redirect("~/home/forbidden", true);以為沒有問題,結果在系統日志中經常看到”服務器無法在已發送 HTTP 標頭之后設置狀。“,於是就找方法解決,無意中,看到別人寫的代碼,還有HandleUnauthorizedRequest這個重寫,於是就用起來了,發現問題解決,現記錄一下。

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //驗證登錄狀態
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }

            //驗證登錄狀態下cookie是否有數據
            var account = UserAuthentication.GetLoginInfo();
            if (account == null)
            {
                return false;
            }
            
            AccountHelper.authService = authService;
            //驗證功能權限
            bool ret = AccountHelper.IsPermission(controllerName, actionName);
            if (!ret && !IsAllowAnonymous)
            {
                //原來用的下面這一句不好用
                //    httpContext.Response.Redirect("~/home/forbidden", true);  
                
                //后來改成這樣一段,也還是不好用              
                //httpContext.Response.Clear();
                //httpContext.Response.BufferOutput = true;
                //if (!httpContext.Response.IsRequestBeingRedirected)
                //{
                //    httpContext.Response.Redirect("~/home/forbidden", true);
                //}
                return false;
            }
            //驗證數據權限


            return true;
        }

        //加上如下的重寫方法,在方法內進行跳轉,問題解決
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {            
            base.HandleUnauthorizedRequest(filterContext);

            filterContext.Result = new RedirectResult("~/home/forbidden");
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM