tags:

views:

145

answers:

1

Why is HttpContext.User.Identity.IsAuthenticated throwing System.NullReferenceException in the base controller from where my all other controllers are inheriting from.

I think the HttpContext is not ready inside the constructor of my base controller.

This is the code:

public abstract class BasicController : Controller
  {
    private IUserProfileRepository _userProfileRepository;

    protected BasicController()
            : this(new UserProfileRepository())
        {}


    protected BasicController(IUserProfileRepository userProfileRepository)
    {
      _userProfileRepository = userProfileRepository;
      if (HttpContext.User.Identity.IsAuthenticated)
      {
        var user = _userProfileRepository.Getuser(HttpContext.User.Identity.Name);
        ViewData["currentlyLoggedInUser"] = user;
      }
      else
      {
        ViewData["currentlyLoggedInUser"] = null;
      }
    }

HttpContext was not ready in the base controller constructor. So this is what I did, now its working fine:

public abstract class BasicController : Controller
  {
    private IUserProfileRepository _userProfileRepository;

    protected BasicController()
            : this(new UserProfileRepository())
        {}


    protected BasicController(IUserProfileRepository userProfileRepository)
    {
      _userProfileRepository = userProfileRepository;
    }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      if (filterContext.HttpContext.User.Identity.IsAuthenticated)
      {
        var user = _userProfileRepository.Getuser(filterContext.HttpContext.User.Identity.Name);
        filterContext.Controller.ViewData["currentlyLoggedInUser"] = user;
      }
      else
      {
        filterContext.Controller.ViewData["currentlyLoggedInUser"] = null;
      }
    }

  }
A: 

Because HttpContext.User has not been set by any authentication module. Are you requiring authenticated users for this site? Did you disable the DefaultAuthenticationModule? Or perhaps the controller instance is created before the AuthenticateRequest event of HttpApplication is fired?

Gonzalo
Yes, I need authentication for this site. I have used "HttpContext.User.Identity.IsAuthenticated" at other places in my code and it works fine
San
And you have <authorization><allow users="?" /></authorization> or similar in your web.config?
Gonzalo
no i dont have this in my web.config
San
Then it is likely that the controller instance is created before the `AuthenticateRequest` event happens.
Gonzalo
Yes thats what even I think..is there someway i can get it some how??
San
I got the solution, look at my updated question above.
San
Nice! I was writing a comment to suggest something like that.
Gonzalo