c# - 给 session 赋值,给对象引用未设置到MVC中对象异常的实例

标签 c# .net asp.net-mvc session controller

问题陈述:

我正在尝试为 MVC Controller 中的 session 对象分配一个值,它给出了异常,因为未将对象引用设置为对象的实例。

我有两个 Controller

  1. 主 Controller
  2. 次要 Controller

当我在主 Controller 中为 session 赋值时它工作正常。但是如果我在辅助 Controller 的 Test() 方法中赋值相同,它会出错。

我在这里做错了什么???

主 Controller :

 public class MainController: Controller
     {
        SecondaryController secCont=new SecondaryController();
        public ActionResult Index(LoginModel loginModel)
          {

            if (ModelState.IsValid)
                {
                 Session["LogID"] = 10;
                  //This is working fine.
                  //Instead of this i want call secCont.Test(); method where value for session assigned, it is giving error.

                }
              return View(loginModel);

           }
     }

二级 Controller :

 public class SecondaryController: Controller
   {
     public void Test()
     {
        Session["LogID"] = 10;
        // Giving Error as **Object reference not set to an instance of an object.**
      }

    }

最佳答案

这是因为 Session 变量仅在 Standard ASP.NET MVC Controller(主 Controller )中可用。为了访问辅助 Controller 中的 session 变量,您应该使用

System.Web.HttpContext.Current.Session["LogID"] = 10;

关于c# - 给 session 赋值,给对象引用未设置到MVC中对象异常的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23629089/

相关文章:

c# - Windows 服务的后台 worker

c# - 匿名函数的强制参数评估

html - 将集合呈现为每行条目数为 "n"的 html 表的最干净方法是什么

c# - 遍历 StartDate 和 EndDate 之间的每一天

asp.net - 我应该在 ASP.NET 中生成 HTML

c# - 如何在 MVC 中为国家和州/省创建选择列表

c# - 如何在ajax调用后重置表单

c# - 如何在linq中设置日期格式 "yyyy-MM-dd hh:mm"?

C# 使用媒体查询发送响应式 HTML 邮件

c# - 运算符 '==' 不能应用于类型 'Type?' 和 'Type?' 的操作数