【问题标题】:Session values in HttpContext.Current.Session in C# set and getC# 中 HttpContext.Current.Session 中的会话值设置和获取
【发布时间】:2020-04-01 06:42:32
【问题描述】:

我在 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;
        }
     } 
}

当我尝试使用 MasterPageDefault.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# session get set


    【解决方案1】:

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

    1. asp .net 的 WebForms
    2. WebApi
    3. MVC

    现在取决于生命周期,HttpContext 是否已初始化。我们需要更多地了解您的具体示例,例如您何时调用和设置,获取会话以便我们为您提供帮助。

    干杯!

    【讨论】:

    • 谢谢我已经编辑了我的第一个问题,请你帮帮我吗?
    • 你在哪里做作业?在构造函数中?
    • 它在 Default.aspx.cs 和 MasterPage 上的分配。请在我的第一个问题中查看 Edit #01
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 2014-07-13
    相关资源
    最近更新 更多