将整页进行缓存,页面中放置了一个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中一切正常
请高手指点

解决方案 »

  1.   

    直接使用传入参数context中的session protected static string GetUserInfoView(HttpContext context)
    {
    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;
    }
      

  2.   

    暂时没看出问题来,不过你的程序写法有点错误if (Session["UserName"].ToString() != "")应该写成if (Session["UserName != null && Session["UserName"].ToString() != "")
    这样不会有异常出现,你原来的写法是只要session为空就马上出异常
      

  3.   

    多谢二楼指导,但将语句改成 context.Session["UserName"] 后刷新时还是会出现错误提示:
    System.NullReferenceException: 未将对象引用设置到对象的实例。请问是什么原因呢?
    注:Session["UserName"]在Global.asax的Session_Start中已做了声明 
      

  4.   

    什么叫做“Session["UserName"]做了声明”呢?不太明白这个意思。这类代码通常应该写为:if (context.Session["UserName"] != null && (string)context.Session["UserName"] != "")我对 ToString 也比较不爱看到(虽然这并没有什么逻辑错误)。
      

  5.   

    当真正缓冲的时候,Session属性似乎并没有。我从来不使用 Substitution。这个东西跟普通的缓存不同,我从来没有测试过它。如果需要片段缓存,把页面拆分为不同的ascx,各个片段自己制定缓存策略。从来不使用Substitution。