【问题标题】:"System.NullReferenceException" for Using Session in MVC在 MVC 中使用 Session 的“System.NullReferenceException”
【发布时间】:2015-02-19 18:41:23
【问题描述】:

在我的 MVC 项目中,我使用像

这样的会话值
var empId = Convert.ToInt32(Session["EmpId"].ToString());

我收到异常:

“在 Project.Web.dll 中发生了“System.NullReferenceException”类型的异常,但未在用户代码中处理。

附加信息:对象引用未设置为对象的实例。"

【问题讨论】:

  • 你检查过 Session["EmpId"] 是否为空?

标签: asp.net-mvc asp.net-mvc-3 session session-variables


【解决方案1】:

当您在空对象上调用方法时会发生此错误。在您的情况下,Session["EmpId"] 的值是 NULL

这意味着您正在调用NULL.ToString(),这是无效的,因此会引发错误。

您可以使用null coaleascing 运算符来避免错误,或者在对其执行任何操作之前简单地检查 null。

解决方案:

if(Session["EmpId"] == null)
 //do something
else
 var empId = Convert.ToInt32(Session["EmpId"].ToString());

您也可以查看我的blog post

【讨论】:

  • 我有同样的问题,但我的属性定义是这样的 get { if (Session["_exportViewModel1"] == null) Session["_exportViewModel1"] = new BG.Indigo.Controls.Utilities. CountrySurveyReportExportVM();返回 (BG.Indigo.Controls.Utilities.CountrySurveyReportExportVM)Session["_exportViewModel1"]; } 设置 { 会话 [“_exportViewModel1”] = 值; }
【解决方案2】:

使用前先检查它是否为空。

var empId = Session["EmapId"] != null ? Convert.ToInt32(Session["EmapId"]) : 0;

【讨论】:

    【解决方案3】:

    您必须检查null,如下所示:-

    var empId = Convert.ToInt32((Session["EmpId"] ?? 0).ToString());
    

    一种更有效的方式来满足您的要求:-

    int temp = 0;
    var empId = int.TryParse( Convert.ToString( Session["EmpId"] ),out temp );
    

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 2023-03-24
      • 2014-11-11
      • 2013-09-18
      • 2010-12-02
      • 1970-01-01
      相关资源
      最近更新 更多