首页 > 解决方案 > C# 中 HttpContext.Current.Session 中的会话值设置和获取

问题描述

我在MasterPage中有一个名为MailContainer的静态类。

MailContainer类中,我为 get /set 定义了属性,如下所示。

public static class MailContainer
{
    public static string TheObjectPropertyEmail
    {
        get
        {
            return HttpContext.Current.Session["TheObjectPropertyEmail"].ToString();
        }
        set
        {
            HttpContext.Current.Session["TheObjectPropertyEmail"] = value;
        }
     } 
}

当我尝试使用MasterPage在Default.aspx.cs上分配如下值时。

MailContainer.TheObjectPropertyEmail = reader["Email"].ToString();

它抛出以下异常。

System.NullReferenceException:对象引用未设置为对象的实例。

在这条线上:

return HttpContext.Current.Session["TheObjectPropertyEmail"].ToString();

我该如何解决 ?

编辑#01

public void Aut()
{
    sql = @String.Format(" SELECT * FROM doTable ");
    sql += String.Format(" WHERE ");
    sql += String.Format(" UPPER(user) IN (?); ");

    using (OdbcConnection myConnectionString =
        new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
    {
        using (OdbcCommand command =
            new OdbcCommand(sql, myConnectionString))
        {
            try
            {
                if (username != null)
                {
                    command.Parameters.AddWithValue("param1", username.ToString().ToUpper());
                    command.Connection.Open();

                    using (OdbcDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                MailContainer.TheObjectPropertyEmail = reader["Email"].ToString();
                            }
                        }
                     }   
                 }                         
            }
            catch (Exception ex)
            {
                throw new ApplicationException("operation failed!", ex);
            }
            finally
            {
                command.Connection.Close();
            }
        }
    }
}

标签: c#sessiongetset

解决方案


在此处检查HttpContext。这是一个 HttpContext 仅在 Web 相关项目中可用,例如

  1. 用于 asp .net 的 WebForms
  2. WebAPI
  3. MVC

现在取决于生命周期,HttpContext 是否已初始化。我们需要更多地了解您在致电和设置时的具体示例,让我们为您提供帮助。

干杯!


推荐阅读