ASP.Net MVC 控制器构造函数显示错误 System.Web.Mvc.Controller.Session.get 返回 null

ASP.Net MVC Controller Constructor shows error System.Web.Mvc.Controller.Session.get returned null

基本上我想从许多企业中过滤当前业务的客户,我想在一个地方(构造函数)完成。这样我就可以在控制器的其余部分轻松查询 db.Customers 。但是当我使用 (Employee)Session["CurrentUser"];它显示错误

System.Web.Mvc.Controller.Session.get 返回空值。

public class SOSRController : Controller
    {
        private BusinessContext db = new BusinessContext();
        public SOSRController()
        {
            Employee employee= (Employee)Session["CurrentUser"];
            db.Customers = (DbSet<Customer>) db.Customers.AsQueryable().Where(x => x.Business.Id == employee.bizId);
        }
        public ActionResult Index()
        {
            List<Customer> LstCust= db.Customers.Where(x => x.Name.Contains("asd")).ToList();
        }
}

或者仅在一个地方过滤 db.Customers 的任何其他解决方案是什么?

成功了。我重写了 Initialize 方法,现在我可以获得会话值。 Constructor是类的概念,Initialize是MVC的概念。

protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);

             Employee employee= (Employee)Session["CurrentUser"];
            db.Customers = (DbSet<Customer>) db.Customers.AsQueryable().Where(x => x.Business.Id == employee.bizId);

        }