ASP .NET MVC 判断用户是否已经登录

总体代码:
在这里插入图片描述
因为登录时我将用户基本信息记录在了cookie里面,先获取这个名称为UserMsg的cookie

HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["UserMsg"];

isLogin 类用于返回状态、状态码、以及所需数据

isLogin MSG = new isLogin();
MSG.State = false;
MSG.Code = 1;

因为账号是12位数的,超出了int的最大长度,所以用long

long? number = Convert.ToInt64(System.Web.HttpContext.Current.Server.UrlDecode(cookie["N"]));

获取cookie里面的保存的密码,登录是已将密码加密,加密后会出现cookie不允许的特殊字符串,所以加密后又把他编码保存

string pass = HttpUtility.UrlDecode(cookie["P"], Encoding.Unicode);

通过cookie保存的账号查询账号信息

User tn = (from tu in myModels.Users
where tu.Number == number
select tu).Single();

再通过查询出来的tn 里面的PasswordID 查询密码表里面对应的密码,并且是当前启用的密码

var tp = (from tu in myModels.Passwords
where tu.PasswordID == tn.PasswordID && tu.State == true
select tu).Single();

对比密码是否和cookie里面的密码相同,否则可能是已经修改了密码或非法操作cookie

if (tp.Password1.Equals(pass))
{

}
else
{

MSG.Txt = "密码错误,请重新登录!";
MSG.Code = 1;
}

密码正确,返回所需数据并重置状态码和状态,状态码0以上都视为错误

Dictionary<string, string> savedImageList = new Dictionary<string, string>();
savedImageList.Add("Name", tn.Name);
savedImageList.Add("ProfilePhotoSrc", tn.ProfilePhotoSrc);
savedImageList.Add("Shibboleth", tn.Shibboleth);
savedImageList.Add("Number", tn.Number.ToString());
savedImageList.Add("Birthday", tn.Birthday.ToString());
savedImageList.Add("UserID", tn.UserID.ToString());
savedImageList.Add("MessageID", tn.MessageID.ToString());
savedImageList.Add("TypeID", tn.TypeID.ToString());

MSG.data = savedImageList;
MSG.State = true;
MSG.Txt = "已登录";
MSG.Code = 0;

最后把isLogin 返回

isLogin类

 public class isLogin
    {  
        /// <summary>
        /// 登录状态
        /// </summary>
        public bool State { get; set; }
        /// <summary>
        /// 返回文本
        /// </summary>
        public string Txt { get; set; }
        /// <summary>
        /// 状态码 0 成功~其余失败
        /// </summary>
        public int Code { get; set; }
        /// <summary>
        /// 数据
        /// </summary>
        public object data { get; set; }
    }
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页