将整页进行缓存,页面中放置了一个Substitution控件动态显示用户信息原码如下<asp:Substitution ID="Substitution1" runat="server" MethodName="GetUserInfoView" />protected static string GetUserInfoView(HttpContext context)
{
string str; if (Session["UserName"].ToString() != "")
{//已登陆时显示
str = "欢迎您 <strong>" + .Session["UserName"].ToString() + "</strong>" +
" <a href='/user/'>个人中心</a> " +
"<a href='/user/Exit.aspx'>退出</a>";
}
else
{//未登陆时显示
str = "欢迎您 <strong>游客</strong>" +
" <a href='/user/Login.aspx'>登陆</a> 或 " +
"<a href='/user/Register.aspx'>注册</a>";
} return str;
}运行后提示错误:
CS0120: 非静态字段、方法或属性“System.Web.UI.UserControl.Session.get”要求对象引用将Session加上命名空间System.Web.HttpContext.Current.Session后首次运行可以显示,但登陆用户后开始报错:
System.NullReferenceException: 未将对象引用设置到对象的实例。程序中的Session["UserName"]在Global.asax的Session_Start中已做了声明
原来没有缓存页时放在Page_Load中一切正常
请高手指点
{
string str; if (Session["UserName"].ToString() != "")
{//已登陆时显示
str = "欢迎您 <strong>" + .Session["UserName"].ToString() + "</strong>" +
" <a href='/user/'>个人中心</a> " +
"<a href='/user/Exit.aspx'>退出</a>";
}
else
{//未登陆时显示
str = "欢迎您 <strong>游客</strong>" +
" <a href='/user/Login.aspx'>登陆</a> 或 " +
"<a href='/user/Register.aspx'>注册</a>";
} return str;
}运行后提示错误:
CS0120: 非静态字段、方法或属性“System.Web.UI.UserControl.Session.get”要求对象引用将Session加上命名空间System.Web.HttpContext.Current.Session后首次运行可以显示,但登陆用户后开始报错:
System.NullReferenceException: 未将对象引用设置到对象的实例。程序中的Session["UserName"]在Global.asax的Session_Start中已做了声明
原来没有缓存页时放在Page_Load中一切正常
请高手指点
{
string str; if (context.Session["UserName"].ToString() != "")
{//已登陆时显示
str = "欢迎您 <strong>" + context.Session["UserName"].ToString() + "</strong>" +
" <a href='/user/'>个人中心</a> " +
"<a href='/user/Exit.aspx'>退出</a>";
}
else
{//未登陆时显示
str = "欢迎您 <strong>游客</strong>" +
" <a href='/user/Login.aspx'>登陆</a> 或 " +
"<a href='/user/Register.aspx'>注册</a>";
} return str;
}
这样不会有异常出现,你原来的写法是只要session为空就马上出异常
System.NullReferenceException: 未将对象引用设置到对象的实例。请问是什么原因呢?
注:Session["UserName"]在Global.asax的Session_Start中已做了声明