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;
}
}
}