コード例 #1
0
ファイル: AccountController.cs プロジェクト: songtaojie/Blog
        /// <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);
        }
コード例 #2
0
ファイル: BaseController.cs プロジェクト: chs1124/OACODE
        /// <summary>
        /// 执行控制器中的方法先执行此方法
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            bool isSucess = false;

            //if (Session["userInfo"] == null)
            if (Request.Cookies["sessionId"] != null)
            {
                string sessionId = Request.Cookies["sessionId"].Value;
                //根据该值查
                object obj = MemcachedHelper.get(sessionId);
                if (obj != null)
                {
                    UserInfo userInfo = SerializeHelper.DeserializeToObject <UserInfo>(obj.ToString());
                    LoginUser = userInfo;
                    isSucess  = true;
                    MemcachedHelper.set(sessionId, obj, DateTime.Now.AddMinutes(20));
                }
                //filterContext.HttpContext.Response.Redirect("/Login/Index");
                //filterContext.Result = Redirect("/Login/Index");
            }
            if (!isSucess)
            {
                filterContext.Result = Redirect("/Login/Index");
            }
        }
コード例 #3
0
        /// <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);
        }
コード例 #4
0
        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");
            }
        }
コード例 #5
0
        public void CollectionStore()
        {
            var client = MemcachedHelper.CreateClient(new MessagePackMapTranscoder());

            GetReadCache().Clear();
            GetWriteCache().Clear();

            client.Store(StoreMode.Add, "listKey", new List <int> {
                0, 1, 2, 3
            }).Is(true);
            client.Get <List <int> >("listKey").Is(0, 1, 2, 3);

            client.Store(StoreMode.Add, "arrayKey", new int[] { 1, 2, 3 }).Is(true);
            client.Get <int[]>("arrayKey").Is(1, 2, 3);

            client.Store(StoreMode.Add, "arrayKey2", new int[] { 1, 2, 3, 4, 5 }).Is(true);
            client.Get <int[]>("arrayKey2").Is(1, 2, 3, 4, 5);

            var values = client.Get(new[] { "listKey", "arrayKey", "arrayKey2" });

            (values["listKey"] as List <int>).Is(0, 1, 2, 3);
            (values["arrayKey"] as int[]).Is(1, 2, 3);
            (values["arrayKey2"] as int[]).Is(1, 2, 3, 4, 5);

            GetReadCache().Count.Is(2);
            GetWriteCache().Count.Is(2);
        }
コード例 #6
0
        public void ObjectStore()
        {
            var client = MemcachedHelper.CreateClient(new MessagePackMapTranscoder());

            GetReadCache().Clear();
            GetWriteCache().Clear();

            client.Store(StoreMode.Add, "objKey", new MyClass {
                MyProperty = 10, MyProperty2 = "test"
            }).Is(true);
            client.Get("objKey").IsNotNull();
            (client.Get("objKey") as MyClass).Is(x => x.MyProperty == 10 && x.MyProperty2 == "test");
            client.Get <MyClass>("objKey").Is(x => x.MyProperty == 10 && x.MyProperty2 == "test");

            client.Store(StoreMode.Add, "genKey", new GenericType <int> {
                MyProperty = 10, MyProperty2 = 100
            }).Is(true);
            client.Get <GenericType <int> >("genKey").Is(x => x.MyProperty == 10 && x.MyProperty2 == 100);

            client.Store(StoreMode.Add, "genKey2", new GenericType <string> {
                MyProperty = 10, MyProperty2 = "hyaku"
            }).Is(true);
            client.Get <GenericType <string> >("genKey2").Is(x => x.MyProperty == 10 && x.MyProperty2 == "hyaku");

            GetReadCache().Count.Is(3);
            GetWriteCache().Count.Is(3);
        }
コード例 #7
0
ファイル: MailController.cs プロジェクト: axel10/insdep-oa
        private void SaveMail(string title, string[] shoujian, string content, HttpPostedFileBase file, bool isDraft, string sessionId)
        {
            string   jsonStr  = MemcachedHelper.Get(sessionId).ToString();
            UserInfo userInfo = SerializeHelper.toJson <UserInfo>(jsonStr);

            MailInfo mailInfo;

            if (file != null)
            {
                mailInfo = new MailInfo
                {
                    Title      = title,
                    Content    = content,
                    SenderId   = userInfo.ID,
                    CreateTime = DateTime.Now,
                    File       = file.FileName,
                    IsDraft    = isDraft
                };
            }
            else
            {
                mailInfo = new MailInfo
                {
                    Title      = title,
                    Content    = content,
                    SenderId   = userInfo.ID,
                    CreateTime = DateTime.Now,
                    IsDraft    = isDraft
                };
            }
            MailInfoService.AddEntity(mailInfo);
            MailInfoService.SaveMailUserInfo(shoujian, mailInfo.Id);
        }
コード例 #8
0
ファイル: AccountController.cs プロジェクト: songtaojie/Blog
        public JsonResult ActiveUser(string key)
        {
            AjaxResult result = new AjaxResult();

            if (MemcachedHelper.Get(key) != null)
            {
                string   userName = MemcachedHelper.Get(key).ToString();
                UserInfo userInfo = this._userService.GetEntity(u => u.UserName == userName);
                if (userInfo == null)
                {
                    result.Success = false;
                    result.Message = "此用户没有注册!";
                }
                else
                {
                    userInfo.Activate = "Y";
                    this._userService.Update(userInfo);
                    result.Success = true;
                }
                MemcachedHelper.Delete(key);
            }
            else
            {
                result.Success = false;
                result.Message = "此激活链接已失效!";
            }

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
コード例 #9
0
ファイル: LoginController.cs プロジェクト: chs1124/OACODE
        public ActionResult UserLogin()
        {
            string validateCode = Session["ValidateCode"] != null ? Session["ValidateCode"].ToString() : string.Empty;

            if (string.IsNullOrEmpty(validateCode))
            {
                return(Content("验证码错误!!!"));
            }
            Session["ValidateCode"] = null;
            string txtCode = Request["vCode"];

            if (!validateCode.Equals(txtCode, StringComparison.InvariantCultureIgnoreCase))
            {
                return(Content("验证码错误!!!"));
            }
            string userName = Request["LoginCode"];
            string userPwd  = Request["LoginPwd"];
            var    userInfo = userInfoService.LoadEntities(u => u.UName == userName && u.UPwd == userPwd).FirstOrDefault();

            if (userInfo != null)
            {
                //Session["userInfo"] = userInfo;
                string sessionId = Guid.NewGuid().ToString();
                MemcachedHelper.set(sessionId, SerializeHelper.SerializeToString(userInfo), DateTime.Now.AddMinutes(20));

                Response.Cookies["sessionId"].Value = sessionId;
                return(Content("ok:登录成功"));
            }
            else
            {
                return(Content("no:登录失败"));
            }
        }
コード例 #10
0
        public void MemcachedCheck()
        {
            var client = MemcachedHelper.CreateClient(new MessagePackMapTranscoder());
            var store  = client.Store(StoreMode.Add, "hugahuga", 100);

            store.Is(true);

            var value = client.Get <int>("hugahuga");

            value.Is(100);
        }
コード例 #11
0
ファイル: UserContext.cs プロジェクト: songtaojie/Blog
 /// <summary>
 /// 清空缓存和session中存的值
 /// </summary>
 public static void ClearUserInfo()
 {
     UserContext.LoginUser = null;
     if (Request.Cookies[ConstInfo.SessionID] != null)
     {
         string sessionId = Request.Cookies[ConstInfo.SessionID].Value;
         MemcachedHelper.Delete(sessionId);
     }
     WebHelper.RemoveCookie(ConstInfo.SessionID);
     WebHelper.RemoveCookie(ConstInfo.CookieName);
 }
コード例 #12
0
ファイル: UserContext.cs プロジェクト: songtaojie/Blog
        /// <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;
        }
コード例 #13
0
 private void _timer_Elapsed(object sender, ElapsedEventArgs e)
 {
     foreach (KeyValuePair <string, IVolatileToken> token in timeCache)
     {
         if (!token.Value.IsCurrent)
         {
             IVolatileToken _token = new AbsoluteExpirationToken(this, TimeSpan.Zero);
             MemcachedHelper.GetInstance().Remove(token.Key);
             timeCache.TryRemove(token.Key, out _token);
         }
     }
 }
コード例 #14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string key = Request["key"] ?? "a";

            Response.Write(string.Format("key:{0}<br/>", key));

            Response.Write(MemcachedHelper.Get(key));
            Response.Write("<br/>");
            Response.Write(MemcachedHelper.Get(key + "test"));
        }
    }
コード例 #15
0
        public ActionResult Logout()
        {
            if (Request.Cookies["sessionId"] != null)
            {
                var key = Request.Cookies["sessionId"].Value;
                MemcachedHelper.Delete(key);
                Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1);
                Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1);
            }

            //return RedirectToAction("Index");
            return(Redirect("/Login/Index"));
        }
コード例 #16
0
        public ActionResult Logout()
        {
            if (Request.Cookies["LoginCookie"] != null)
            {
                if (Request.Cookies["UName"] != null)
                {
                    Request.Cookies["UName"].Expires = DateTime.Now.AddDays(-1);
                    Request.Cookies["UPwd"].Expires  = DateTime.Now.AddDays(-1);
                }

                MemcachedHelper.DeleteMemcachedData(Request.Cookies["LoginCookie"].Value);
            }
            return(Redirect("/Login/Index"));
        }
コード例 #17
0
        private static void ClearCacheProvider(CachingProviderType cachingProvider)
        {
#if NETFULL
            if (cachingProvider == CachingProviderType.Memcached)
            {
                MemcachedHelper.ClearDatabase("127.0.0.1", 11211);
            }
#endif
            if (cachingProvider == CachingProviderType.Redis)
            {
                RedisHelper.ClearDatabase("localhost", 0);
            }

            if (cachingProvider == CachingProviderType.Couchbase)
            {
                CouchbaseHelper.ClearDatabase("http://localhost:8091", "default", "password", "default");
            }
        }
コード例 #18
0
ファイル: UserContext.cs プロジェクト: songtaojie/Blog
        /// <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);
        }
コード例 #19
0
ファイル: MailController.cs プロジェクト: axel10/insdep-oa
        public ActionResult Inbox(string query)
        {
            string   sessionId = Request.Cookies["sessionId"]?.Value ?? "";
            string   jsonStr   = MemcachedHelper.Get(sessionId).ToString();
            UserInfo userInfo  = SerializeHelper.toJson <UserInfo>(jsonStr);

            if (string.IsNullOrEmpty(query))
            {
                var mailInfos = MailInfoService.GetAllReceiveMail(userInfo.ID).ToList();
                ViewBag.MailInfoList = mailInfos;
                return(View());
            }
            else
            {
                var mailInfos = MailInfoService.GetAllReceiveMail(userInfo.ID, query).ToList();
                ViewBag.MailInfoList = mailInfos.ToList();
                return(View());
            }
        }
コード例 #20
0
        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:登录失败"));
            }
        }
コード例 #21
0
        public ActionResult LoginUser()
        {
            string sessionValidateCode = Session["ValidateCode"] != null ? Session["ValidateCode"].ToString() : string.Empty;

            if (string.IsNullOrEmpty(sessionValidateCode))
            {
                return(Content("N:验证码错误!"));
            }
            if (!Request["vCode"].Equals(sessionValidateCode, StringComparison.CurrentCultureIgnoreCase))
            {
                return(Content("N:验证码错误!"));
            }

            string uName     = Request["LoginCode"];
            string uPwd      = Request["LoginPwd"];
            var    loginUser = UserInfoService.LoadEntities(u => u.UName == uName && u.UPwd == uPwd).FirstOrDefault();

            if (loginUser == null)
            {
                Session["ValidateCode"] = null;
                return(Content("N:用户名密码错误!"));
            }
            //  Session["LoginUser"] = loginUser;
            else
            {
                string sessionCookie = Guid.NewGuid().ToString();
                MemcachedHelper.SetMemcachedData(sessionCookie, JsonSerializeHelper.JsonSerialize(loginUser), DateTime.Now.AddMinutes(20));
                Response.Cookies["LoginCookie"].Value = sessionCookie;
            }
            if (Request["checkRemember"] != null)
            {
                HttpCookie cp1 = new HttpCookie("UName", loginUser.UName);
                HttpCookie cp2 = new HttpCookie("UPwd", MD5Helper.GetMD5String(MD5Helper.GetMD5String(loginUser.UPwd)));
                cp1.Expires = DateTime.Now.AddDays(5);
                cp2.Expires = DateTime.Now.AddDays(5);
                HttpContext.Response.Cookies.Add(cp1);
                HttpContext.Response.Cookies.Add(cp2);
            }
            return(Content("Y:用户登陆成功!"));
        }
コード例 #22
0
ファイル: AccountController.cs プロジェクト: songtaojie/Blog
        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));
        }
コード例 #23
0
 // GET: Login
 public ActionResult Index()
 {
     if (Request.Cookies["UName"] != null && !string.IsNullOrEmpty(Request.Cookies["UName"].Value))
     {
         string cookieUName = Request.Cookies["UName"].Value;
         string cookieUPwd  = Request.Cookies["UPwd"].Value;
         var    loginUser   = UserInfoService.LoadEntities(u => u.UName == cookieUName).FirstOrDefault();
         if (cookieUPwd == MD5Helper.GetMD5String(MD5Helper.GetMD5String(loginUser.UPwd)))
         {
             string sessionCookie = Guid.NewGuid().ToString();
             MemcachedHelper.SetMemcachedData(sessionCookie, JsonSerializeHelper.JsonSerialize(loginUser), DateTime.Now.AddMinutes(20));
             Response.Cookies["LoginCookie"].Value = sessionCookie;
             Response.Cookies["UName"].Expires     = DateTime.Now.AddDays(5);
             Response.Cookies["UPwd"].Expires      = DateTime.Now.AddDays(5);
             return(Redirect("/Home/Index"));
         }
         else
         {
             Response.Cookies["UName"].Expires = DateTime.Now.AddDays(-1);
             Response.Cookies["UPwd"].Expires  = DateTime.Now.AddDays(-1);
         }
     }
     return(View());
 }
コード例 #24
0
ファイル: UserContext.cs プロジェクト: songtaojie/Blog
        /// <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));
            }
        }
コード例 #25
0
    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"));
        }
    }
コード例 #26
0
 static void Main(string[] args)
 {
     //CallResultConst.RegisterDescription();
     //var t = CallResult.Success;
     //var str = CallResult.Success.GetDescription();
     //var t1 = CallResultConst.RFIDTAGUSED;
     //var t2 = CallResultConst.ILlegeTag;
     //if (t1 == t2)
     //{
     //    Console.WriteLine(t1==t2);
     //}
     //var str1 = CallResultConst.ILlegeTag.GetDescription();
     //var str2 = CallResultConst.RFIDTAGUSED.GetDescription();
     try
     {
         MemcachedHelper.SetCache("a", "b");
         System.Console.WriteLine(MemcachedHelper.GetCache("a"));
         System.Console.ReadKey();
     }
     catch (System.Exception ex)
     {
         System.Console.WriteLine(ex.Message);
     }
 }
コード例 #27
0
        public void Init()
        {
            var client = MemcachedHelper.CreateClient(new ProtoTranscoder());

            client.FlushAll();
        }
コード例 #28
0
        public void Init()
        {
            var client = MemcachedHelper.CreateClient(new MessagePackMapTranscoder());

            client.FlushAll();
        }
コード例 #29
0
ファイル: BaseController.cs プロジェクト: kiddVS/OA
        // GET: Base
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            bool isExist = false;

            if (filterContext.HttpContext.Request.Cookies["LoginCookie"] != null)
            {
                object login = MemcachedHelper.GetMemcachedData(filterContext.HttpContext.Request.Cookies["LoginCookie"].Value);
                if (login != null)
                {
                    LoginUser = JsonSerializeHelper.JsonDeSerialize <UserInfo>(login.ToString());
                    isExist   = true;
                    MemcachedHelper.SetMemcachedData(filterContext.HttpContext.Request.Cookies["LoginCookie"].Value, login, DateTime.Now.AddMinutes(20));
                    if (LoginUser.UName == "jc")
                    {
                        return;
                    }
                    string urlPath    = Request.Url.AbsolutePath;
                    string httpMethod = Request.HttpMethod.ToUpper();
                    //spring的容器创建业务类的实例
                    IApplicationContext ctx = ContextRegistry.GetContext();
                    CUP.PE.OA.IBLL.IActionInfoService ActionInfoService = (CUP.PE.OA.IBLL.IActionInfoService)ctx.GetObject("ActionInfoService");
                    CUP.PE.OA.IBLL.IUserInfoService   UserInfoService   = (CUP.PE.OA.IBLL.IUserInfoService)ctx.GetObject("UserInfoService");
                    if (ActionInfoService.LoadEntities(u => u.Url == urlPath && u.HttpMethod == httpMethod).FirstOrDefault() != null)
                    {
                        var userInfo = UserInfoService.LoadEntities(u => u.ID == LoginUser.ID).FirstOrDefault();
                        //1.从用户→权限进行过滤
                        var user2Action = (from u in userInfo.R_UserInfo_ActionInfo
                                           select u).Where(u => u.ActionInfo.Url == urlPath && u.ActionInfo.HttpMethod == httpMethod).FirstOrDefault();
                        if (user2Action != null)
                        {
                            if (user2Action.IsPass == true)
                            {
                                return;
                            }
                            else
                            {
                                filterContext.Result = Redirect("/Error.html");
                            }
                        }
                        else
                        {
                            //2.从用户→角色→权限进行过滤
                            var user_Role_Action = (from u in userInfo.RoleInfo
                                                    from a in u.ActionInfo
                                                    where a.Url == urlPath && a.HttpMethod == httpMethod
                                                    select a).FirstOrDefault();
                            if (user_Role_Action != null)
                            {
                                return;
                            }
                            else
                            {
                                filterContext.Result = Redirect("/Error.html");
                                return;
                            }
                        }
                    }
                    else
                    {
                        filterContext.Result = Redirect("/Error.html");
                        return;
                    }
                }
            }
            if (!isExist)
            {
                filterContext.Result = Redirect("/Login/Index");
                return;
            }
        }
コード例 #30
0
ファイル: HomeController.cs プロジェクト: xie454801015/NCMVC
        //[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());
        }