tags:

views:

48

answers:

2

I am creating an application and want that determine what pages are displayed in a menu based on the user login. I am creating an application controller abstract class to pass data back to the master page but the http context is not initialized when the code get called. I was trying to avoid filters but I am lost. Any thoughts?

public abstract class ApplicationController : Controller
{

    public ApplicationController()        
    {
        string myuser = this.User.Identity.Name;           
    }

}
A: 

try to make your .ctor protected

public abstract class ApplicationController : Controller 
{
    protected ApplicationController()
    {
        string myuser = this.User.Identity.Name;
    } 
}

also make sure you are not missing this using directive:

using System.Web.Mvc;
Yassir
what difference does it make if the ctor is made protected?
San
@San : read this http://msdn.microsoft.com/en-us/library/ms229047.aspx
Yassir
+1  A: 

Yassir is correct about using protected constructors in abstract classes. But you are correct that it doesn't solve your problem--the HttpContext still ain't quite populated yet so you get null reference exceptions.

Anyhow, the solution is simple--override the Initialize method of the controller:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    string myuser = this.User.Identity.Name;
    base.Initialize(requestContext);
}
Wyatt Barnett