其他分享
首页 > 其他分享> > 使用HttpRuntime.Cache缓存自定义令牌

使用HttpRuntime.Cache缓存自定义令牌

作者:互联网

封装HttpRuntime.Cache,网上一大堆

 public class CacheHelper
    {
        //HttpRuntime.Cache.Insert("myname", "战三", null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(5));//滑动过期
        //HttpRuntime.Cache.Insert("myname", "战三", null, DateTime.Now.AddSeconds(5), System.Web.Caching.Cache.NoSlidingExpiration);//绝对过期
        //HttpRuntime.Cache.Add("myname", "李四", null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(5), System.Web.Caching.CacheItemPriority.Normal, null);
        //HttpRuntime.Cache.Add("myname", "李四", null, DateTime.Now.AddSeconds(5), TimeSpan.FromSeconds(5), System.Web.Caching.CacheItemPriority.Normal, null);
        //读取
        //绝对过期:到了指定时间以后便会失效。
        //滑动过期:在指定时间内无访问请求便失效。

        /// <summary>
        /// 获取数据缓存
        /// </summary>
        /// <param name="CacheKey">键</param>
        public static object GetCache(string CacheKey)
        {
            Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey];
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject)
        {
            Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject);
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
        {
            Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration)
        {
            HttpRuntime.Cache.Insert(CacheKey, objObject, null, absoluteExpiration, Cache.NoSlidingExpiration);//绝对过期
        }
        

        /// <summary>
        /// 移除指定数据缓存
        /// </summary>
        public static void RemoveAllCache(string CacheKey)
        {
            Cache _cache = HttpRuntime.Cache;
            _cache.Remove(CacheKey);
        }

        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static void RemoveAllCache()
        {
            Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                _cache.Remove(CacheEnum.Key.ToString());
            }
        }
    }

封装返回令牌

/// <summary>
    /// 用户令牌记录数据库
    /// </summary>
    public class op_user_token
    {
        public int uid { get; set; }
        public string utoken { get; set; }
        public DateTime sysdate { get; set; }
    }

    /// <summary>
    /// 返回令牌
    /// </summary>
    public class UserToken
    {
        public bool ack
        {
            get
            {
                return string.IsNullOrWhiteSpace(ErrorMsg);
            }
        }
        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMsg { get; set; }
        /// <summary>
        /// ip地址
        /// </summary>
        public string token { get; set; }
        /// <summary>
        /// 令牌申请时间
        /// </summary>
        public DateTime sysdate { get; set; }
    }

生成令牌

/// <summary>
        /// 获取令牌
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public UserToken GetToken(string caccount, string password)
        {
            var user = _userBLL.GetModel(caccount);
            if (user != null)
            {
                if (user.password == password)
                {
                    return CreateToken(user);
                }
                else
                {
                    return CreteModel("", "密码错误", DateTime.Now);
                }
            }
            else
            {
                return CreteModel("", "账号错误", DateTime.Now);
            }
        }

        /// <summary>
        /// 创建令牌
        /// 2小时内有效
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [NonAction]
        private UserToken CreateToken(op_user model)
        {
            try
            {
                var data = CacheHelper.GetCache(_token) as List<op_user_token>;
                if (data == null)
                {
                    data = new List<op_user_token>();
                    return AddToken(data, model.id);
                }
                else
                {
                    var nowdata = data.Where(it => it.sysdate > DateTime.Now.AddHours(-2)).ToList();
                    var token = nowdata.Where(it => it.uid == model.id).FirstOrDefault();
                    if (token == null)
                    {
                        return AddToken(nowdata, model.id);
                    }
                    else
                    {
                        return CreteModel(token.utoken, "", DateTime.Now);
                    }
                }
            }
            catch (Exception ex)
            {
                return CreteModel("", ex.ToString(), DateTime.Now);
            }
        }

        [NonAction]
        private UserToken AddToken(List<op_user_token> data, int uid)
        {
            string utoken = Guid.NewGuid().ToString();
            op_user_token token = new op_user_token();
            token.uid = uid;
            token.utoken = utoken;
            token.sysdate = DateTime.Now;
            data.Add(token);
            CacheHelper.SetCache(_token, data, DateTime.Now.AddHours(2));
            _tokenBLL.AddToken(token);
            return CreteModel(utoken, "", token.sysdate);
        }

        [NonAction]
        private UserToken CreteModel(string utoken, string mess, DateTime sysdate)
        {
            return new UserToken() { ErrorMsg = mess, token = utoken, sysdate = sysdate };
        }

验证令牌

 /// <summary>
    /// 自定义此特性用于接口的身份验证
    /// </summary>
    public class RequestAuthorizeAttribute : AuthorizeAttribute
    {
        //重写基类的验证方式,加入我们自定义的Ticket验证
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            try
            {
                //从http请求的头里面获取身份验证信息,验证是否是请求发起方的ticket
                var utoken = actionContext.Request.Headers.GetValues("token").FirstOrDefault();
                if (!string.IsNullOrEmpty(utoken))
                {
                    var data = CacheHelper.GetCache("token") as List<op_user_token>;
                    if (data != null)
                    {
                        var nowdata = data.Where(it => it.sysdate > DateTime.Now.AddHours(-2)).ToList();
                        var token = nowdata.Where(it => it.utoken == utoken).FirstOrDefault();
                        if (token == null)
                        {
                            HandleUnauthorizedRequest(actionContext);
                        }
                        else
                        {
                            base.IsAuthorized(actionContext);
                        }
                    }
                    else
                    {
                        HandleUnauthorizedRequest(actionContext);
                    }
                }
                else
                {
                    var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
                    bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
                    if (isAnonymous) base.OnAuthorization(actionContext);
                    else HandleUnauthorizedRequest(actionContext);
                }
            }
            catch (System.Exception)
            {
                HandleUnauthorizedRequest(actionContext);
            }
        }
    }

使用时候,放在方法上或控制器上

/// <summary>
        /// 添加一条mac记录数据
        /// </summary>
        [RequestAuthorize]
        [HttpPost]
        public int AddMac(op_user_mac model)
        {
            return _user_macBLL.Add(model);
        }

 

标签:string,自定义,Cache,DateTime,token,HttpRuntime,null,public
来源: https://www.cnblogs.com/shuaimeng/p/13769524.html