views:

45

answers:

1

I currently have a abstract controller class that I all my controllers inherit from. I want to be able to use the current user (IPrinciple) object in my master page. I read that I could use the contructor of my abstract base controller class, that is I could do something like

public BaseController()
    {
        ViewData["UserName"] = this.User.Identity.Name;
    }

I could then access ViewData["UserName"] etc from my master page. My problem is that this.User is null at this point. Does anybody know of a different approach?

Thanks in advance.

+2  A: 

You could write an ActionFilter and in the OnActionExecuted event put the user inside ViewData:

public class UserActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        filterContext.Controller.ViewData["UserName"] = filterContext.HttpContext.User.Identity.Name;
    }
}

And then decorate your base controller with this attribute:

[UserActionFilter]
public abstract class BaseController: Controller
{ }
Darin Dimitrov
That works a treat! Thanks very much for your help!
bplus