/// <summary> /// 判断Cookie信息 /// </summary> private void CheckCookieInfo() { if (Request.Cookies["cp1"] != null && Request.Cookies["cp2"] != null) { var userName = Request.Cookies["cp1"].Value; var userPwd = Request.Cookies["cp2"].Value; //判断cookie中储存的用户密码和用户名是否正确 var userInfo = UserInfoBll.LoadEntities(u => u.UserName == userName) .FirstOrDefault(); if (userInfo != null) { //注意:用户密码一定要加密以后保存到数据库 if (WebCommon.GetMd5String(WebCommon.GetMd5String(userInfo.UserPwd)) == userPwd) { var sessionId = Guid.NewGuid().ToString(); MemcachedHelper.Set(sessionId, SerializerHelper.SerializerToString(userInfo), DateTime.Now.AddMinutes(20)); Response.Cookies["sessionId"].Value = sessionId; Response.Redirect("/Home/Index"); } } } //删除Cookies Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1); Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); bool isSuccess = false; if (Request.Cookies["sessionId"] != null) { string sessionId = Request.Cookies["sessionId"].Value; object obj = MemcachedHelper.Get(sessionId); if (obj != null) { UserInfo userInfo = SerializeHelper.toJson <UserInfo>(obj.ToString()); LoginUser = userInfo; isSuccess = true; MemcachedHelper.Set(sessionId, obj.ToString(), DateTime.Now.AddMinutes(60)); if (LoginUser.UName == "123") { return; } } } if (!isSuccess) { filterContext.Result = Redirect("/login/index"); } }
/// <summary> /// 发送邮件,激活账号 /// </summary> /// <param name="userName"></param> /// <param name="toEmail"></param> /// <returns></returns> public async Task <bool> SendEmail(string userName, string toEmail) { Guid key = Guid.NewGuid(); MemcachedHelper.Set(key.ToString(), userName, DateTime.Now.AddMinutes(30)); var checkUrl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + "/uc/account/activation?key=" + key; string mailAccount = WebHelper.GetAppSettingValue("MailAccount") , mailPwd = WebHelper.GetAppSettingValue(""); await Task.Run(() => { EmailHelper email = new EmailHelper() { MailPwd = mailPwd, MailFrom = mailAccount, MailSubject = "欢迎您注册 海星·博客", MailBody = EmailHelper.TempBody(userName, "请复制打开链接(或者右键新标签中打开),激活账号", "<a style='word-wrap: break-word;word-break: break-all;' href='" + checkUrl + "'>" + checkUrl + "</a>"), MailToArray = new string[] { toEmail } }; email.SendAsync((s, ex) => { if (!s && ex != null) { Logger.Error("邮箱发送失败", ex); } }); }); return(true); }
/// <summary> /// 更新缓存和session中存的值 /// </summary> public static void UpdateUser(UserInfo userInfo) { string sessionId = WebHelper.GetCookieValue(ConstInfo.SessionID); if (!string.IsNullOrEmpty(sessionId)) { string jsonData = JsonConvert.SerializeObject(userInfo); MemcachedHelper.Set(sessionId, jsonData, DateTime.Now.AddHours(2)); } UserContext.LoginUser = userInfo; }
/// <summary> /// 验证Session中(即Memcached中)是否有数据 /// </summary> /// <returns></returns> public static UserInfo ValidateSession() { UserInfo userInfo = null; string sessionId = WebHelper.GetCookieValue(ConstInfo.SessionID); if (!string.IsNullOrEmpty(sessionId)) { object value = MemcachedHelper.Get(sessionId); if (value != null) { string jsonData = value.ToString(); userInfo = JsonConvert.DeserializeObject <UserInfo>(jsonData); UserContext.LoginUser = userInfo; //模拟滑动过期时间,就像Session中默认20分钟那这样 MemcachedHelper.Set(sessionId, value, DateTime.Now.AddHours(2)); } } return(userInfo); }
public ActionResult UserLogin() { /* string vCode = Session["vCode"] != null ? Session["vCode"].ToString() : ""; * * if (string.IsNullOrEmpty(vCode)) * { * return Content("no:验证码错误"); * } * * Session["vCode"] = null; * string txtCode = Request["code"]; * if (txtCode == null) * { * return Content("no:验证码为空"); * } * if (!txtCode.Equals(vCode,StringComparison.InvariantCultureIgnoreCase)) * { * return Content("no:验证码错误"); * }*/ string userName = Request["username"]; string userPwd = Request["password"]; var userInfo = UserInfoService.LoadEntities(u => u.UName == userName && u.UPwd == userPwd).FirstOrDefault(); if (userInfo != null) { string sessionId = Guid.NewGuid().ToString(); bool isSuccess = MemcachedHelper.Set(sessionId, SerializeHelper.toJsonString(new{ ID = userInfo.ID, UName = userInfo.UName }), DateTime.Now.AddMinutes(200)); string o = MemcachedHelper.Get(sessionId).ToString(); if (!isSuccess) { return(Content("no:登录失败,session设置失败")); } Response.Cookies["sessionId"].Value = sessionId; return(Content("ok:登录成功")); } else { return(Content("no:登录失败")); } }
public async Task <JsonResult> RegisterUser(UserInfoDTO info) { AjaxResult result = new AjaxResult(); UserInfo userInfo = null; if (ModelState.IsValid) { userInfo = MapperManager.Map <UserInfo>(info); userInfo = this._userService.Insert(userInfo, out result); } if (result.Success) { await SendEmail(info.UserName, info.Email); result.Message = "已发送激活链接到邮箱,请尽快激活。"; result.Resultdata = Request[ConstInfo.returnUrl]; string sessionId = Guid.NewGuid().ToString(); Response.Cookies[ConstInfo.SessionID].Value = sessionId.ToString(); string jsonData = JsonConvert.SerializeObject(userInfo); MemcachedHelper.Set(sessionId, jsonData, DateTime.Now.AddMinutes(20)); } return(Json(result, JsonRequestBehavior.AllowGet)); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string key = Request["key"] ?? "a"; string value = Request["value"] ?? "a08888"; Response.Write(string.Format("key:{0}, value: {1}<br/>", key, value)); if (MemcachedHelper.Set(key, value)) { Response.Write("保存成功1<br/>"); } Response.Write(MemcachedHelper.Get(key) + "<br/>"); if (MemcachedHelper.Set(key + "test", value + "_test", 3)) { Response.Write("保存成功2<br/>"); } Response.Write(MemcachedHelper.Get(key + "test")); Response.Write("<br/>" + DateTime.Now.ToString("yyyyMMdd HH:mm:ss")); } }
/// <summary> /// 把用户信息存储在Memcached缓存中 /// </summary> public static void CacheUserInfo(UserInfo userInfo, bool isRemember = false) { if (userInfo == null) { return; } //模拟Session string sessionId = Guid.NewGuid().ToString(); WebHelper.SetCookieValue(ConstInfo.SessionID, sessionId.ToString(), DateTime.Now.AddHours(2)); string jsonData = JsonConvert.SerializeObject(userInfo); MemcachedHelper.Set(sessionId, jsonData, DateTime.Now.AddHours(2)); //记住用户名,添加7天的缓存 if (isRemember) { Dictionary <string, string> user = new Dictionary <string, string>(); user.Add(nameof(userInfo.UserName), userInfo.UserName); user.Add(nameof(userInfo.PassWord), userInfo.PassWord); string jsonUser = JsonConvert.SerializeObject(user); string desUser = Hx.Common.Security.SafeHelper.DESEncrypt(jsonUser); WebHelper.SetCookieValue(ConstInfo.CookieName, desUser, DateTime.Now.AddDays(7)); } }
//[Authorize(AuthenticationSchemes = "user_info")] public IActionResult Index() { var userId = User.Claims.FirstOrDefault(x => x.Type == "UserName")?.Value; ViewData["user"] = userId; //throw new System.Exception("Throw Exception"); string s = Request.Query["s"]; var path = AppContext.BaseDirectory; #region --测试日志-- // Logger.Info("普通信息日志-----------"); // Logger.Debug("调试日志-----------"); // Logger.Error("错误日志-----------"); // Logger.Fatal("异常日志-----------"); // Logger.Warn("警告日志-----------"); // Logger.Trace("跟踪日志-----------"); // Logger.Log(NLog.LogLevel.Warn, "Log日志------------------"); // //_logger.LogInformation("你访问了首页"); // //_logger.LogWarning("警告信息"); // //_logger.LogError("错误信息"); #endregion #region --测试redis-- RedisHelper.Default.StringSet("redis", "redis" + DateTime.Now, TimeSpan.FromSeconds(1000000)); ViewData["redis"] = RedisHelper.Default.StringGet("redis"); //RedisHelper.Default.KeyDelete("redis"); #endregion #region --测试sql-- DataTable dt = Dbl.ZZCMS.CreateSqlDataTable("select * from nc_manager"); ViewData["mng"] = dt; #endregion #region --测试memcachedcore-- //MCached.Set("depend2", "core", "memcached-core" + DateTime.Now, 59); //var re = MCached.Get("depend", "core"); //ViewData["mhelper1"] = re; //MemcachedHelper.Remove("core"); MemcachedHelper.Set("core", "memcachedcore" + DateTime.Now, 10); var mh = MemcachedHelper.Get("core"); ViewData["mhelper"] = mh; //这种方式暂未找到合适赋值,待研究,赋值赋不上。 //删/增/取memcachedcore5 //var cacheKey = "memcachedcore"; //await _memcachedClient.AddAsync(cacheKey, "memcachedcore" + DateTime.Now, 60); ////_memcachedClient.Add(cacheKey, "memcachedcore" + DateTime.Now, 60);//此方法赋不上值 ////var result = _memcachedClient.Get(cacheKey); //var result = _memcachedClient.Get(cacheKey); //_memcachedClient.Remove(cacheKey); //ViewData["memcachedcore"] = result.ToString(); #endregion return(View()); }