试图从会话中检索值

本文关键字:检索 会话 | 更新日期: 2023-09-27 17:49:38

我尝试创建一个新的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);

但是它给了我同样的错误

试图从会话中检索值

这意味着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"]为空。

抛出错误,因为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();
}

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

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