我试图将用户重定向到其他操作,如果他们的电子邮件地址尚未验证。问题是,我不希望他们被注销,我只是想重定向他们。当我在控制器的OnAuthorization中执行此操作时,它按照预期重定向,但用户未通过身份验证。我不确定这是为什么。我的代码如下所示:OnAuthorization中的MVC重定向导致授权失败
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);
}
}
}
注意:我删除了不必要的代码以使其更清晰。 _applicationService.CurrentUser被当前用户填充 - 并且用户在到达该点时已被正确验证。但是在重定向之后,用户不再被认证。
如何在不影响内置用户授权的情况下实现此重定向?我试过把我的代码放到OnActionExecuting中,我也尝试过在自定义的ActionFilterAttribute中实现它,但是无论我把这个重定向放在哪里,都会阻止'User'(例如:System.Security.Principal .IPrincipal Controller.User)获得身份验证。
我在这里错过了什么?希望这是有道理的。任何帮助非常感谢。
在回答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);
}
你能告诉你如何验证用户 - 你的LogOn行动? –
@DarinDimitrov - 我已按要求添加了我的登录操作。 – soupy1976
这正是我一直在寻找的!节省了很多时间 – JosephDoggie