问题陈述:
我正在尝试为 MVC Controller 中的 session 对象分配一个值,它给出了异常,因为未将对象引用设置为对象的实例。
我有两个 Controller
- 主 Controller
- 次要 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/