使用HttpRuntime.Cache快取自定義令牌
阿新 • • 發佈:2020-10-05
封裝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); }