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

登录信息存入session时成功读取失败。

一个手机网页,用户登录后,信息可以正常存入session,后面读的时候提示获取usersession出错
session.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;

namespace wap
{
    [Serializable]
    public class UserSession
    {
        /// <summary>
        /// 初始化用户登录Session
        /// </summary>
        public UserSession(int _id, string _loginname, int _roleid, string _roleflag, int _allowflag, int _status, int _companyid, string _companyname, string _realname, int _companytype, bool _ismanager, int _grade, int _pid, int _companyflag)
        {
            this.Id = _id;
            this.LoginName = _loginname;
            this.RoleId = _roleid;
            this.RoleFlag = _roleflag;
            this.AllowFlag = _allowflag;
            this.Status = _status;
            this.CompanyId = _companyid;
            this.CompanyName = _companyname;
            this.RealName = _realname;
            this.CompanyType = _companytype;
            this.IsManager = _ismanager;
            this.Grade = _grade;
            this.Pid = _pid;
            this.CompanyFlag = _companyflag;
        }

        public int Id;
        public string LoginName;
        public int RoleId;
        public string RoleFlag;
        public int AllowFlag;
        public int Status;
        public int CompanyId;
        public string CompanyName;
        public string RealName;
        public int CompanyType;
        public bool IsManager;
        public int Grade;
        public int Pid;
        public int CompanyFlag;
    }

    [Serializable]
    public class SessionBox
    {
        private SessionBox() { }

        #region 用户Session操作

        /// <summary>
        /// 檢測User Session是否存在
        /// </summary>
        /// <returns></returns>
        public static bool CheckUserSession()
        {
            object o = System.Web.HttpContext.Current.Session["USER"];
            if (o == null)
                return false;
            else
                return true;

        }



        /// <summary>
        /// 登记User Session
        /// </summary>
        /// <param name="userinfo"></param>
        public static void CreateUserSession(UserSession userinfo)
        {
            //if (System.Web.HttpContext.Current.Session["USER"] == null)
            //{
                HttpContext.Current.Session["USER"] = userinfo;
            //}
        }

        /// <summary>
        /// 获取User Session
        /// </summary>
        /// <returns></returns>
        public static UserSession GetUserSession()
        {
            object o = System.Web.HttpContext.Current.Session["USER"];
            if (o == null) throw new ExceptionSession("读取UserSession失败。");
            else return (o as UserSession);----------一就是这一名报错        }

        /// <summary>
        /// 移除User Session
        /// </summary>
        public static void RemoveUserSession()
        {
            object o = System.Web.HttpContext.Current.Session["USER"];
            if (o != null) System.Web.HttpContext.Current.Session.Remove("USER");
        }

        #endregion

    }
    public class ExceptionSession : Exception
    {
        public ExceptionSession() : base() { }
        public ExceptionSession(string message) : base(message) { }
        public ExceptionSession(string message, Exception inner) : base(message, inner) { }
    }
}
--------------------编程问答-------------------- login.ashx

using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using RsLib;
using RsDBUtility;
using RsModel;
using System.Web.SessionState;

namespace  wap
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>

    public class Handler1 : IHttpHandler, IRequiresSessionState, IReadOnlySessionState
    {
       
        public void ProcessRequest(HttpContext context)
        {
            string txtName = context.Request.Form["username"].Trim();
            string txtPassword = context.Request.Form["pwd"];
            if (Checkusername(txtName, txtPassword))
            {
                int uid;
                string ret = userlogin(txtName , txtPassword, out uid);
                if (uid > 0 && ret == "成功登录")
                {
                    Users model = new Users();
                    model = GetUserModel(uid);
                    model.RoleFlag = CheckRoleFlag(model.RoleFlag, model.RoleId);
                    UserSession us = new UserSession(model.Id,
                            model.UserName,
                            model.RoleId,
                            model.RoleFlag,
                            model.AllowFlag,
                            model.Status,
                            model.CompanyId,
                            model.CompanyName,
                            model.RealName,
                            model.CompanyType,
                            model.IsManager,
                            model.Grade,
                            model.Pid,
                            model.CompanyFlag);
                    SessionBox.CreateUserSession(us);
                    //context.Response.Buffer = true;
                    //context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
                    //context.Response.AddHeader("pragma", "no-cache");
                    //context.Response.AddHeader("cache-control", "");
                    //context.Response.CacheControl = "no-cache";
                    
                    context.Response.ContentType = "text/vnd.wap.wml";
                    context.Response.Redirect("main.aspx");
                }
                else
                {
                    context.Response.ContentType = "text/vnd.wap.wml";
                    context.Response.Redirect("error.aspx", false);
                }
            }
            else
            {
                //System.Web.HttpContext.Current.Response.Write("您的用户名或密码错误");
                context.Response.Redirect("error.aspx", false);
            }
        }
        public bool  Checkusername(string username, string password)
        {
            int uid;
            string  str = userlogin(username, password, out uid);
            if (str=="成功登录")
            {
                return true;
            }
            else
            {
                return false;
            }                           
        }

        public static string  userlogin(string username,string passwrod,out int uid)
        {
            string str;
            int ret = Login(username, SecurityEncryption.MD5(passwrod, 32), out uid);
            switch (ret)
            {
                case 0:
                    str = "用户不存在"; break;
                case 1:
                    str = "密码错误"; break;
                case 2:
                    str = "用户锁定"; break;
                case 3:
                    str = "成功登录";  break;
                default:
                    str = "未知错误"; break;
            }
            return str;
        }
        public static int Login(string UserName, string pwd, out int uid)
        {
            IDataParameter[] parameters = {
                     new SqlParameter("@userName", SqlDbType.NVarChar,128),
                     new SqlParameter("@userPassword", SqlDbType.NVarChar,128),
                     new SqlParameter("@uid",SqlDbType.Int),
                     new SqlParameter("@ret",SqlDbType.Int)
                                        };
            parameters[0].Value = UserName;
            parameters[1].Value = pwd;
            parameters[2].Direction = ParameterDirection.Output;
            parameters[3].Direction = ParameterDirection.Output;
            int rows;
            SqlServerHelper.RunProcedure("m_spUserLogin", parameters, out rows);
            int ret = int.Parse(parameters[3].Value.ToString());
            uid = int.Parse(parameters[2].Value.ToString());
            return ret;
        }
        public Users GetUserModel(int UserID)
        {
            IDataParameter[] parameters = {
                    new SqlParameter("@Id",SqlDbType.Int)
                                          };
            parameters[0].Value = UserID;
            RsModel.Users model = new RsModel.Users();
            DataSet ds = SqlServerHelper.RunProcedure("m_spUserInfo", parameters, "UserInfo");
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                model.Id = UserID;
                model.UserName = dr["UserName"].ToString();
                model.RealName = dr["RealName"].ToString();
                model.Sex = dr["Sex"].ToString();
                model.Mobile = dr["Mobile"].ToString();
                model.Phone = dr["Phone"].ToString();
                model.CardNo = dr["CardNo"].ToString();

                model.CreateName = dr["CreateName"].ToString();
                model.CreateTime = DateTime.Parse(dr["CreateTime"].ToString());
                model.ModifyName = dr["ModifyName"].ToString();
                if (dr["ModifyTime"].ToString() != "")
                    model.ModifyTime = DateTime.Parse(dr["ModifyTime"].ToString());
                model.VerifyName = dr["VerifyName"].ToString();
                if (dr["VerifyTime"].ToString() != "")
                    model.VerifyTime = DateTime.Parse(dr["VerifyTime"].ToString());
                if (dr["LastTime"].ToString() != "" && dr["LastTime"] != null)
                {
                    model.LastTime = DateTime.Parse(dr["LastTime"].ToString());
                }
                if (dr["Status"].ToString() != "")
                {
                    model.Status = int.Parse(dr["Status"].ToString());
                }
                model.AllowFlag = int.Parse(dr["AllowFlag"].ToString());
                model.IsOnline = int.Parse(dr["IsOnline"].ToString());
                model.Remark = dr["Remark"].ToString();
                //读取角色
                model.RoleId = int.Parse(dr["RoleId"].ToString());
                model.RoleFlag = dr["RoleFlag"].ToString();
                if (dr["CompanyId"].ToString() != "")
                {
                    DataTable dt = ds.Tables[1];
                    model.CompanyId = int.Parse(dr["CompanyId"].ToString());
                    if (dt.Rows.Count > 0)
                    {
                        model.CompanyType = int.Parse(dt.Rows[0]["CompanyType"].ToString());
                        if (dr["Id"].ToString() == dt.Rows[0]["Manager"].ToString())
                            model.IsManager = true;
                        else
                            model.IsManager = false;
                        model.CompanyName = dt.Rows[0]["CompanyName"].ToString();
                        model.Grade = int.Parse(dt.Rows[0]["Grade"].ToString());
                        model.Pid = int.Parse(dt.Rows[0]["Pid"].ToString());
                        model.CompanyFlag = int.Parse(dt.Rows[0]["AllowFlag"].ToString());
                    }
                    else
                    {
                        model.CompanyType = 1;
                        model.IsManager = true;
                        model.CompanyName = "";
                        model.Grade = 0;
                        model.Pid = 0;
                        model.CompanyFlag = 1;
                    }
                }
                return model;
            }
            else
            {
                return null;
            }
        }
        protected string CheckRoleFlag(string rf, int rid)
        {
            string[] r = rf.Split(',');
            string[] n = Role.GroupRole[rid].Split(',');
            if (r.Length >= n.Length)
                return rf;
            else
            {
                string o = "";
                for (int i = r.Length; i < n.Length; i++)
                {
                    o += "," + n[i];
                }
                return rf + o;
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
--------------------编程问答-------------------- main.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace wap
{

    public partial class main : System.Web.UI.Page
    {
        public string un;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                un = SessionBox.GetUserSession().RealName;
            }
        }
       
            
        }
    }
--------------------编程问答-------------------- 会不会你穿的类不是UserSession 而是null? --------------------编程问答-------------------- 在main.aspx页面,我用了<%=un%>来显示登录的用户名。
在登录的过程中对session存入信息没有问题,
在读的时候,运行到
 public static UserSession GetUserSession()
        {
            object o = System.Web.HttpContext.Current.Session["USER"];
            if (o == null) throw new ExceptionSession("读取UserSession失败。");
            else return (o as UserSession  ///////这里报错:读取UserSession失败
        }

--------------------编程问答--------------------
引用 3 楼  的回复:
会不会你穿的类不是UserSession 而是null?

??引用肯定是没有错的 --------------------编程问答-------------------- 那位大神知道,,速来回答一下,搞了两天,都是这个错误。3Q3Q
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,