【问题标题】:trying to retrieve a value from a session试图从会话中检索值
【发布时间】:2014-03-11 19:05:11
【问题描述】:

我试图创建一个新的 Customer 对象并从中检索 Cid 值,如下所示:

Line 32:         Customer temp = new Customer();
Line 33:         temp =(Customer)Session["customer"];
Line 34:         int id = temp.Cid;

但我收到此错误:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request.      Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object."

我也尝试过这样做:

int id = Convert.Toint(temp.Cid);

但它给了我同样的错误

【问题讨论】:

标签: c# asp.net session nullreferenceexception code-behind


【解决方案1】:

这意味着Session["customer"]null。您需要先检查Session["customer"] 是否为null

if(Session["customer"] != null){

 Customer temp =(Customer)Session["customer"];
 int id = temp.Cid;
}

如果Session["customer"]null,那么您需要检查以确保您正确设置了Session["customer"]

如果你用谷歌搜索object reference not set to an instance of an object stack overflow,你会注意到这个错误被问了很多。 object reference not set to an instance of an object,就是它所说的。 Session["customer"] 是一个会话变量,它可以保存对对象的引用。如果您尚未设置该引用,则 Session["customer"] 为空。

【讨论】:

    【解决方案2】:

    它会抛出错误,因为Session["customer"] 为空。在转换为 Customer 之前,您需要确保 Session["customer"] 不为空。

    请参阅以下示例中的 SessionCustomer -

    <asp:Label runat="server" ID="Label1" />
    <asp:Button ID="PostBackButton" OnClick="PostBackButton_Click" 
        runat="server" Text="Post Back" />
    
    public class Customer
    {
        public int Id { get; set; }
    }
    
    public Customer SessionCustomer
    {
        get
        {
            var customer = Session["Customer"] as Customer;
            return customer ?? new Customer();
        }
        set { Session["Customer"] = value; }
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            SessionCustomer = new Customer() {Id = 1};
        }
    }
    
    protected void PostBackButton_Click(object sender, EventArgs e)
    {
        // Display the Customer ID 
        Label1.Text = SessionCustomer.Id.ToString();
    }
    

    【讨论】:

      【解决方案3】:

      我会先赋值,然后检查该值是否为空。

      Customer temp = Session["customer"] as Customer;
      if (temp != null) {
        int id = temp.Cid;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-10
        • 1970-01-01
        • 1970-01-01
        • 2010-10-20
        • 2023-03-07
        • 1970-01-01
        • 2017-10-28
        相关资源
        最近更新 更多