Custom Attribute above a controller function

Gaui picture Gaui · Nov 9, 2012 · Viewed 7.8k times · Source

I want to put [FirstTime] attribute above a controller function and then create a FirstTimeAttribute that has some logic that checks whether the user has entered his name, and redirects him to /Home/FirstTime if he hasn't.

So Instead of doing:

public ActionResult Index()
{
    // Some major logic here
    if (...)
        return RedirectToAction("FirstTime", "Home");

    return View();
}

I would just do:

[FirstTime]
public ActionResult Index()
{
    return View();
}

Is this possible?

Answer

Mihai picture Mihai · Nov 9, 2012

Sure. Do something like

public class FirstTimeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(filterContext.HttpContext.Session != null)
        {
          var user = filterContext.HttpContext.Session["User"] as User;
          if(user != null && string.IsNullOrEmpty(user.FirstName))
              filterContext.Result = new RedirectResult("/home/firstname");
          else
          {
              //what ever you want, or nothing at all
          }
         }
    }
}

And just use [FirstTime] attribute on your actions