当前位置:编程学习 > C#/ASP.NET >>

关于 HttpContext.Current.Session["值"] 的存取问题, 代码如下:

这是在一个页面里面的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using FInancingModels;
using FinancingBLL;
using System.Web.Services;
using System.Runtime.Remoting.Contexts;
using System.Web.SessionState; 
public partial class Login : System.Web.UI.Page{
 [WebMethod(EnableSession = true)]
        public static string UserLogin(string userLogin, string userPass)
        {
            UserInfo user = UserInfoManager.GetUserLoginId(userLogin);
            if (user != null)
            {
                if (user.UserPassword == userPass)
                {
                    HttpContext.Current.Session["login"] = user;
                                        return "true";

                }
                else
                {
                    return "false";
                }
            }
            else
            {
                return "false";
            }
        }


然后一个重写Page 类的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using FInancingModels;

namespace FinancingUI
{
    public class PageBase:Page
    {
        /// <summary>
        /// 重写page类的方法,验证用户是否登录
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            //if (((UserInfo)Session["login"]) == null)//如果没登录就跳到登录页面
            //{
            //    Response.Redirect("Login.aspx");
            //}
            //else
            //{
            //    Response.Redirect("FinanceView.aspx");
            //}
            if (HttpContext.Current.Session["login"] == null)//如果没登录就跳到登录页面
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                Response.Redirect("FinanceView.aspx");
            }
        }
    }
}

为什么 PageBase这个重新Page类方法里面的 HttpContext.Current.Session["login"]  老是得不到值啊? 请赐教......
--------------------编程问答-------------------- 在Page_Load方法被执行之前,System.Web.UI.Page类的很多对象是不能使用的,比如:Application,Session等。

你应该在base.OnInit(e)之前执行先PageLoad
this.Load += new System.EventHandler(this.Page_Load);
--------------------编程问答-------------------- 结贴率0.00% 比较纠结 --------------------编程问答-------------------- 我不是重写方法
 protected override void OnInit(EventArgs e)

可是
 protected  void OnInit(EventArgs e)

还有直接写
 if (Session["login"] == null)//如果没登录就跳到登录页面

成功,一直这么用
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,