Geeks With Blogs

News Please visit me at my new blog!!

profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers
"free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
more about the Gospel
And then listen to Francis Chan speaking at LifeLight in SD.



Programming and Learning from SD

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.
Posted on Tuesday, August 12, 2014 3:59 PM MVC | Back to top


Comments on this post: MVC OnActionExecuting to Redirect

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Aligned | Powered by: GeeksWithBlogs.net