最近在做权限时候,直接在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"); }