我使用以下代码从类文件中分配会话变量。但我收到错误消息“对象引用未设置为对象的实例”。
HttpContext.Current.Session.Add("UserSession", "dsafd");
答案 0 :(得分:2)
实现目标的正确方法是(在c#中使用在线工具进行翻译,注意检查()或[]):
if ((Session("UserSession") == null))
{
//example with simple string
Session.Add("UserSession", "thisIsASimpletString");
//Exmple with an Object NOTE: the constructor new if is required or you may handling in exception like your
List<string> list = new List<string>();
Session.Add("UserSession", list);
}
else
{
//different case where session exist
Session("UserSession") = "thisIsASimpletString";
//case with object
List<string> list = new List<string>();
Session("UserSession") = list;
}
如果此asnser符合您的目标标记作为答案。
如果你在谈论一个设置会话值的类,你需要将上下文传递给你的calss,但这不是一个好主意。最好将类中的值返回给会话或将对象(类)保存到会议也是
示例中的(但未建议并假设您填写了姓名和姓氏属性):
protected void Page_Load(object sender, EventArgs e)
{
MyObject _class = new MyObject(HttpContext.Current);
_class.SetNameAndSurname();
Response.Write(Session("UserInfo").ToString);
}
private class MyObject
{
public void SetNameAndSurname()
{
if ((this.Context.Session("UserInfo") == null)) {
this.Context.Session.Add("UserInfo", this.Surname + "-" + this.Name);
} else {
this.Context.Session("UserInfo") = this.Surname + "-" + this.Name;
}
}
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private string _Surname;
public string Surname
{
get { return _Surname; }
set { _Surname = value; }
}
private HttpContext _context;
public HttpContext Context
{
get { return _context; }
set { _context = value; }
}
public MyObject(HttpContext Context)
{
this._context = Context;
}
public MyObject()
{
}
}
在示例中还有许多其他方法可以实现相同的目标:SameClass具有属性,方法:
protected void Load()
{
MyObject _class = new MyObject;
_class.surname="Surname";
_class.name="Name";
context.Session.add("UserInfo"),_class.name + "-" + _class.surname);
}
所有都取决于你的阶级,方法,属性和逻辑。