Why is User (as in User.Identity.Name) null in my abstract base controller?

The answer to this problem is actually quite simple. I can't execute the code from within the constructor for reasons pointed out by Raimond, but I can do it outside the constructor.

So what I did was overriding onActionExecuting() in the base controller class (I created a custom Attribute for it, but just overriding the method should also work) and then do my user lookup from there.

Now it works as expected and I have no repeated code.


Can you grab this using something like:

HttpContext currentContext = HttpContext.Current;
string userName = currentContext.User.Identity.Name;

Or is the HttpContext always empty??

Could you set the httpContext through the constructor of the abstract class? and use it this way?


My guess would be that the Controller's base constructor is not filling in the User, but that it is only known later when the ControllerContext is set for the Controller. You should check this in the documentation about the lifecycle of an MVC application, (the one here will probably do, although it might be a bit out of date since it's for the preview version), or just check the source code of MVC.

from the code that I have of MVC (also a preview version, but that should be fine): (In Controller)

 public IPrincipal User {
            get {
                return HttpContext == null ? null : HttpContext.User;
            }
        }

...

public HttpContextBase HttpContext {
        get {
            return ControllerContext == null ? null : ControllerContext.HttpContext;
        }
    }

I don't see en an implementation of a default constructor in the code. That would prove that the ControllerContext is null at the time of construction.

So you should execute your code somewhere else.


The User property is not assigned until after the Controller has been instantiated, but you can gain early access from your constructor with:

System.Web.HttpContext.Current.User