OnAuthorization中的MVC重定向导致授权失败

sou*_*976 5 c# asp.net-mvc forms-authentication asp.net-mvc-3

我正在尝试将用户重定向到另一个操作,如果他们的电子邮件地址尚未经过验证.问题是,我不希望它们被注销,我只是想重定向它们.当我在OnAuthorization中为控制器执行此操作时,它会按预期重定向,但用户未经过身份验证.我不确定为什么会这样.我的代码看起来像这样:

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        //_applicationService.CurrentUser is populated correctly at this point
        // from Controller.User
        if (_applicationService.CurrentUser != null)
        {
            if (_applicationService.CurrentUser.EmailVerified != true)
            {
                var url = new UrlHelper(filterContext.RequestContext);
                var verifyEmailUrl = url.Action("EmailVerificationRequired", "Account", null);
                filterContext.Result = new RedirectResult(verifyEmailUrl);
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

注意:我删除了不必要的代码以使其更清晰._applicationService.CurrentUser由当前用户填充 - 当用户到达该点时,用户已经过正确的身份验证.但在重定向之后,用户不再经过身份验证.

如何在不影响内置用户授权的情况下实现此重定向?

我已经尝试将我的代码放入OnActionExecuting,并且我也尝试在自定义的ActionFilterAttribute中实现它,但是无论我把这个重定向放在哪里都会阻止'User'(即:System.Security.Principal.IPrincipal Controller.用户)获得身份验证.

我在这里错过了什么?希望这是有道理的.任何帮助非常感谢.

为响应Darin对我的登录操作的请求:

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Login(LoginViewModel model, string returnUrl)
    {
        string errorMessage = "The username or password is incorrect";

        if (ModelState.IsValid)
        {
            if (_contextExecutor.ExecuteContextForModel<LoginContextModel, bool>(new LoginContextModel(){                    
              LoginViewModel = model  
            }))
            {
                ViewBag.CurrentUser = _applicationService.CurrentUser;
                _formsAuthenticationService.SetAuthCookie(model.LoginEmailAddress, model.RememberMe);

                if (_applicationService.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }

                return RedirectToAction("Index", "Home").Success("Thank you for logging in.");
            }
            else
            {
                errorMessage = "Email address not found or invalid password.";
            }
        }

        return View(model).Error(errorMessage);
    }
Run Code Online (Sandbox Code Playgroud)

sou*_*976 5

好吧,我现在已经找到我哪里出错了。问题是我有点傻,而且我没有完全理解我在做的事情时发生了什么:

filterContext.Result = new RedirectResult(verifyEmailUrl);
Run Code Online (Sandbox Code Playgroud)

我没有意识到我实际上是在以此开始一个新请求,我错误地认为我只是重定向到另一个操作。现在看来很明显,这将是一个新的请求。

所以,问题是我的EmailVerificationRequired操作没有授权用户,因此当它执行此操作时,当前用户为空。因此,修复方法是向该操作添加授权,现在一切都很好。

谢谢你们的帮助。