【问题标题】:ASP.Net MVC Controller Constructor shows error System.Web.Mvc.Controller.Session.get returned nullASP.Net MVC 控制器构造函数显示错误 System.Web.Mvc.Controller.Session.get 返回 null
【发布时间】:2020-02-28 11:33:54
【问题描述】:

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

System.Web.Mvc.Controller.Session.get 返回 null。

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?

【问题讨论】:

    标签: asp.net-mvc-4 session model-view-controller constructor


    【解决方案1】:

    成功了。我重写了 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);
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多