0

I want to be able to globally access the logged-in user in (Controllers, HtmlHelpers and other helper classes) throughout the whole application without getting exceptions that User is null and with the ability to handle guests (not-logged-in users).

Should this be handled within my UsersRepository? If so, how to? or is there a better approach?

Ken D
  • 5,880
  • 2
  • 36
  • 58
  • 2
    I use static context for that -> http://stackoverflow.com/questions/3964989/how-to-pass-current-user-information-to-all-layers-in-ddd/3969014#3969014 – Arnis Lapsa Jul 15 '11 at 14:01

2 Answers2

1

You can create custom identity and principal classes. Your custom identity class can extend whatever you are currently using and can then simply add the extra information you need.

Then in a global action filter, simply overwrite the current principal with your customized one. Then you can access it from anywhere like a normal identity, but if you need your additional information, you simply cast it to your custom identity class. Which will grant you access to your additional information.

Daniel Young
  • 436
  • 1
  • 3
  • 6
0

You can write a custom action filter that is executed on every request (you register it as a global filter). This filter would load the user (from the user´s repository for example) and put it the http context for example or in the ViewData.

EDIT:

Ok, the code for the filter could look like this (in this case, it loads the user to the ViewData collection). I didn´t consider anonymous users here.

public class LoadUserToViewDataAttribute : ActionFilterAttribute
{
    private IUserRepository _userRepository;

    public LoadUserToViewDataAttribute(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var controller = filterContext.Controller;
        var userName = filterContext.HttpContext.User.Identity.Name;
        var user = _repository.GetUser(userName);

        controller.ViewData.Add("CurrentUser", user);
    }
}
uvita
  • 4,124
  • 1
  • 27
  • 23