I created an ApplicationController.cs that all other Controllers inherit. I’m trying to use this Controller to capture the user’s full name from the DB, set to ViewBag & capture in layout.cshtml.
I aslo created a session variable in Global.asax that captures the user’s login. My problem is that the Session variable is null in ApplicationController.cs. However, the session variable is populated properly in all the children Controllers. Here’s my ApplicationController.cs code:
public abstract class ApplicationController : Controller
{
private SkadPROEntities db = new SkadPROEntities();
public SkadPROEntities SkadProDB
{
get { return db; }
}
public ApplicationController()
{
//string[] currentUserString = User.Identity.Name.Split('\\');
//string myCurrentUser = currentUserString[1];
//string myCurrentUser = Session["currentUser"].ToString();
var empQuery = from employee in db.PRO_LSN_EMPLOYEE_OBJ
//where employee.LSN_Security_Nbr == Session["currentUser"].ToString()
where employee.LSN_Security_Nbr == "bhopkins"
select employee;
string firstName = "";
foreach (var myEmployee in empQuery)
{
firstName = myEmployee.LSN_cf_First_Name;
}
ViewBag.FirstName = firstName;
ViewBag.EmpName = "Bill Test";
}
}
Why is the session variable null in ApplicationController.cs, but populated in all the children Controllers?
You can’t access session variables in constructors. Presumably you’re trying to access the session variable within the actions of your children constructors, not their constructors.
See Session null in ASP.Net MVC Controller Constructors