MVC OnActionExecuting to Redirect

Posted by Aligned on Geeks with Blogs See other posts from Geeks with Blogs or by Aligned
Published on Tue, 12 Aug 2014 08:59:16 GMT Indexed on 2014/08/18 16:25 UTC
Read the original article Hit count: 535

Filed under:

Originally posted on: http://geekswithblogs.net/Aligned/archive/2014/08/12/mvc-onactionexecuting-to-redirect.aspx

I recently had the following requirements in an MVC application:

Given a new user that still has the default password

When they first login

Then the user must change their password and optionally provide contact information

I found that I can override the OnActionExecuting method in a BaseController class.

public class BaseController : Controller
{
    [Inject]
    public ISessionManager SessionManager { get; set; }
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // call the base method first
        base.OnActionExecuting(filterContext);

        // if the user hasn't changed their password yet, force them to the welcome page
        if (!filterContext.RouteData.Values.ContainsValue("WelcomeNewUser"))
        {
            var currentUser = this.SessionManager.GetCurrentUser();
            if (currentUser.FusionUser.IsPasswordChangeRequired)
            {
                filterContext.Result = new RedirectResult("/welcome");
            }
        }
    }
}

Better yet, you can use an ActionFilterAttribute (and here) and apply the attribute to the Base or individual controllers.

/// <summary>
/// Redirect the user to the WelcomePage if the FusionUser.IsPasswordChangeRequired is true;
/// </summary>
public class WelcomePageRedirectActionFilterAttribute : ActionFilterAttribute
{
    [Inject]
    public ISessionManager SessionManager { get; set; }

    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        base.OnActionExecuting(actionContext);

        // if the user hasn't changed their password yet, force them to the welcome page
        if (actionContext.RouteData.Values.ContainsValue("WelcomeNewUser"))
        {
            return;
        }

        var currentUser = this.SessionManager.GetCurrentUser();
        if (currentUser.FusionUser.IsPasswordChangeRequired)
        {
            actionContext.Result = new RedirectResult("/welcome");
        }
    }
}

 

[WelcomePageRedirectActionFilterAttribute]
public class BaseController : Controller
{
  ...
}
 
The requirement is now met.

© Geeks with Blogs or respective owner

Related posts about mvc