P.Brian.Mackey
P.Brian.Mackey

Reputation: 44295

MVC3 - Access User context in Controller base class

I have the following code in a view

@User.Identity.Name

Works fine.

The same code in a custom controller base class doesn't work. The User object is null

public class AdminBaseController : Controller
    {
        public AdminBaseController()
        {    
            string userId = User.Identity.Name;                
             //if(!AnAdmin)
                 //redirect to UnauthorizedPage

I want to use this base class in place of System.Web.MVC.Controller as the base for all my Administration screens. This way I can redirect anybody that is not an admin (NTLM authentication).

Why the nulls? How do I get to my context? (HttpContext and something called ControllerContext are null too)


After some tinkering, things are null in the Controller constructors. The Action Methods work fine. Question still stands, but it appears I need help choosing an alternative implementation.

Upvotes: 2

Views: 3454

Answers (2)

Andre Fly
Andre Fly

Reputation: 166

I just tried to access the 'Name'-property in a function within a controller class. That wasn't an issue and it wasn't null.

My best guess is that you can't access this object in the constructor of a controller.

Upvotes: 0

Tomas Voracek
Tomas Voracek

Reputation: 5914

You should use Authorization filter, ASP.NET MVC Authorization. Also check Understanding Action Filters.

Or you can override Initialize method on Controller, User object will be initialized.

Upvotes: 4

Related Questions