c# - 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();
}
}
}
}
解决方案
在此处检查HttpContext。这是一个 HttpContext 仅在 Web 相关项目中可用,例如
- 用于 asp .net 的 WebForms
- WebAPI
- MVC
现在取决于生命周期,HttpContext 是否已初始化。我们需要更多地了解您在致电和设置时的具体示例,让我们为您提供帮助。
干杯!
推荐阅读
- c# - 为什么我不能在这里使用 SQLite 命令生成器?
- python - 使用多处理池在 python 中加速 TFLite 推理
- angular - 在 npm 上拆分和发布后如何维护 Angular 模块
- c# - 使用 C# 对象创建复杂的 JSON
- mql4 - MQL4 问题 如何在 EA 中打开多个订单
- docker - phpmyadmin 无法使用 docker-compose 连接到 mariadb:数据包乱序
- oop - 在使用 »super« 之前访问静态方法
- r - R如何根据现有数据创建列/特征
- python - scrapy 中的项目加载器字段是否可重用?
- react-native - React Native 中的预定本地通知