問題:在MVC的過濾器中驗證用戶狀態時報如下錯誤:
無法在發送 HTTP 標頭之后進行重定向。 跟蹤信息: 在 System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent)
在 System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
解決:
在驗證用戶身份的時候首先要到第三方獲取用戶的openid,這時需要跳轉到第三方頁面,然后回到到當前頁面鏈接,如果沒有綁定則再次跳轉到登錄頁面。過濾器代碼如下:
public class Logged : ActionFilterAttribute, IAuthorizationFilter { ………略……… public void OnAuthorization(AuthorizationContext filterContext) { string openid = XXXXXX.GetOpenId();//在獲取openid時XXXXXX.GetOpenId()已經跳轉,代碼略 if (string.IsNullOrEmpty(openid)) { filterContext.Result = new RedirectResult("https://www.****.com/login");//在獲取openid時頁面已經跳轉,這里就不要再次跳轉了,否則報錯:無法在發送 HTTP 標頭之后進行重定向。 return; } ………略……… } ………略……… }
修改后的代碼:
public class Logged : ActionFilterAttribute, IAuthorizationFilter { ………略……… public void OnAuthorization(AuthorizationContext filterContext) { string openid = XXXXXX.GetOpenId();//在獲取openid時XXXXXX.GetOpenId()已經跳轉 if (string.IsNullOrEmpty(openid)) { filterContext.Result = new ContentResult();//終止Action繼續向下執行 return; } ………略……… } ………略……… }