public async Task <List <BlogArticle> > GetBlogs() { var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" }); var blogArticleList = new List <BlogArticle>(); if (redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticleList = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticleList = await blogArticleServices.Query(s => s.bID > 5); redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2)); } return(blogArticleList); }
public async Task <List <BlogArticle> > GetBlogs() { // 获取配置信息 var con = _options.Value.RedisCaching.ConnectionString; // var connect = AppsettingsHelper.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" }); List <BlogArticle> blogArticles = new List <BlogArticle>(); if (_redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticles = _redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticles = await _blogArticleServices.GetBlogs(); _redisCacheManager.Set("Redis.Blog", blogArticles, TimeSpan.FromHours(2)); } return(blogArticles); }
public IActionResult GenerateJWTToken() { try { bool ismyOpenId = _redisCacheManager.Get("myOpenId"); bool ismySessionKey = _redisCacheManager.Get("mySessionKey"); string OpenId = string.Empty; string SessionKey = string.Empty; if (ismyOpenId && ismySessionKey) { OpenId = _redisCacheManager.GetValue("myOpenId").ToString().Trim('"'); SessionKey = _redisCacheManager.GetValue("mySessionKey").ToString().Trim('"'); } if (OpenId == "") { throw new Exception("OpenId为空,获取token失败!"); } string userId = OpenId + ";" + SessionKey; string jwtStr = string.Empty; bool suc = false; TokenModel tokenModel = new TokenModel { OpenId = OpenId }; jwtStr = JwtHelper.IssueJwt(tokenModel);//登录,获取到一定规则的 Token 令牌 suc = true; _redisCacheManager.Set(jwtStr, userId, TimeSpan.FromHours(2)); return(Ok(new { success = suc, token = jwtStr })); } catch (Exception err) { _logger.Error(typeof(AuthController), "获取token失败!", new Exception(err.Message)); return(FailedMsg(err.Message)); } }
public async Task <object> Get(int id, int page = 1, string bcategory = "技术博文") { int intTotalCount = 6; int TotalCount = 1; List <BlogArticle> blogArticleList = new List <BlogArticle>(); if (redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticleList = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticleList = await blogArticleServices.Query(a => a.bcategory == bcategory); redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2)); } TotalCount = blogArticleList.Count() / intTotalCount; blogArticleList = blogArticleList.OrderByDescending(d => d.bID).Skip((page - 1) * intTotalCount).Take(intTotalCount).ToList(); foreach (var item in blogArticleList) { if (!string.IsNullOrEmpty(item.bcontent)) { item.bRemark = (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Length >= 200 ? (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Substring(0, 200) : (HtmlHelper.ReplaceHtmlTag(item.bcontent)); int totalLength = 500; if (item.bcontent.Length > totalLength) { item.bcontent = item.bcontent.Substring(0, totalLength); } } } return(Ok(new { success = true, page = page, pageCount = TotalCount, data = blogArticleList })); }
public async Task <List <Advertisement> > Get(int id) { var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });//按照层级的顺序,依次写出来 var advertisementList = new List <Advertisement>(); if (redisCacheManager.Get <object>("Redis.Doctor") != null) { advertisementList = redisCacheManager.Get <List <Advertisement> >("Redis.Doctor"); } else { advertisementList = await advertisementServices.Query(d => d.Id == id); redisCacheManager.Set("Redis.Doctor", advertisementList, TimeSpan.FromHours(2)); } return(advertisementList); }
/// <summary> /// 获取用户的角色权限 /// </summary> /// <param name="userId"></param> /// <returns></returns> private async Task <List <string> > GetRolePermission(string userId) { var key = CacheConstantKey.Create(CacheConstantKey.PERMISSION_ROLE_PERMISSION, userId); if (redisCacheManager.Exists(key)) { return(redisCacheManager.Get(key).Split(",").ToList()); } List <string> userRoles = await GetUserRole(userId); List <string> rolePermissions = new List <string>(); foreach (var item in await sysRolePermissionRepository.QueryAsync(w => userRoles.Contains(w.RoleID.ToString()))) { rolePermissions.Add(item.PermissionID.ToString()); } redisCacheManager.Set(key, string.Join(",", rolePermissions)); return(rolePermissions); }
public async Task <List <BlogArticle> > GetBlogs() { // var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });//按照层级的顺序,依次写出来 List <BlogArticle> blogArticleList = new List <BlogArticle>(); if (_redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticleList = _redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticleList = await _blogArticleServices.Query(d => d.bID > 5); _redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2));//缓存2小时 } return(blogArticleList); }
//[Authorize(Policy = "SystemOrAdmin")] //[ApiExplorerSettings(GroupName = "V1")] //[CustomRoute(ApiVersions.V2, "Get")] public async Task <PageModel <BlogArticle> > Get(int id, int page = 1) { //每页大小 var pageSize = 10; //var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });//按照层级的顺序,依次写出来 List <BlogArticle> blogArticleList = new List <BlogArticle>(); blogArticleList = await _blogArticleServices.GetBlogs(); // 你可以用这种包括的形式 using (MiniProfiler.Current.Step("开始加载数据:")) { //先查找Redis缓存中有没有这个数据,有就直接带出来,不需要做DB操作,没有的话更新缓存,缓存时间为2小时 if (_redisCacheManager.Get <object>("Redis.Blog") != null) { // 也可以直接这么写 MiniProfiler.Current.Step("从Redis服务器中加载数据:"); blogArticleList = _redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { // 也可以直接这么写 MiniProfiler.Current.Step("从MSSQL服务器中加载数据:"); blogArticleList = await _blogArticleServices.GetBlogs(); _redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2));//缓存2小时 } MiniProfiler.Current.Step("处理成功之后,开始处理最终数据:"); var pageModel = new PageModel <BlogArticle> { page = page, pageCount = (blogArticleList.Count + pageSize - 1) / pageSize, dataCount = blogArticleList.Count, PageSize = pageSize, data = blogArticleList.Skip((page - 1) * pageSize).Take(pageSize).ToList(), success = true }; //blogArticleList = await _blogArticleServices.GetBlogs(); //_redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2));//缓存2小时 return(pageModel); } }
public async Task <List <BlogArticle> > GetBlogs() { var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });//按照层级的顺序,依次写出来 List <BlogArticle> blogArticleList = new List <BlogArticle>(); //Controller使用Redis缓存 if (redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticleList = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticleList = await blogArticleServices.getBlogs(); redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2));//缓存2小时 } return(blogArticleList); }
/// <summary> /// 发送消息给指定用户 /// </summary> /// <param name="SenderId">发送人Id</param> /// <param name="SenderName">发送人名称</param> /// <param name="ReceiverId">接收人ID</param> /// <param name="Message">发送消息</param> /// <returns></returns> public async Task SendMessage(string SenderId, string SenderName, string ReceiverId, string Message) { var SignalRModel = _redisCacheManager.Get <SignalRModel>(ReceiverId.ToString()); if (SignalRModel != null) { await Clients.Client(SignalRModel.SignalRConnectionId).SendAsync("ReceiveMessage", SenderName, Message); } else { await Clients.All.SendAsync("ReceiveMessage", SenderName, Message); } }
public async Task <List <BlogArticle> > getBlogs() { var connetct = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" }); List <BlogArticle> blogArticles = new List <BlogArticle>(); if (redisCacheManager.Get <Object>("Redis.Blog") != null) { blogArticles = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticles = await this.blogArticleServices.getBlogs(); redisCacheManager.Set("Redis.Blog", blogArticles, TimeSpan.FromHours(2)); } return(blogArticles); }
/// <summary> /// 查询用户是否存在 /// </summary> /// <returns></returns> public async Task <Wx_UserInfo> GetUserInfoExists(string tokenHeader) { string OpenId = string.Empty; bool isKey = _redisCacheManager.Get(tokenHeader); if (isKey) { OpenId = _redisCacheManager.GetValue(tokenHeader).ToString().Split(";")[0].Trim('"'); } return(await Task.Run(() => { var result = db.Queryable <Wx_UserInfo>().Where(it => it.OpenId == OpenId).FirstAsync(); return result; })); }
/// <summary> /// 在自定义策略处理器中调用方法 /// </summary> /// <param name="roleArr"></param> /// <returns></returns> public async Task <List <RoleActionModel> > GetRoleAction(Guid [] roleArr) { var RoleModuleList = new List <RoleActionModel>(); var Rolelist = await _roleRepositoty.GetAllListAsync(x => roleArr.Contains(x.Id)); //根据Httpcontext存储的角色名称获取角色ID var RoleAssig = await _roleRightAssigRepository.GetAllListAsync(x => Rolelist.Select(s => s.Id).Contains(x.RoleId)); //根据角色ID获取到所有的权限 var Btnlist = await _buttonRepositoty.GetAllListAsync(x => x.IsDrop == false); //获取所有的按钮 List <SysMenu> Menulist = new List <SysMenu>(); if (await _redisCacheManager.Get(Appsettings.app(new string[] { "CacheOptions", "Menukey" }))) //判断菜单缓存是否存在,如果存在则取缓存不存在则取数据库 { Menulist = await _redisCacheManager.GetList <SysMenu>(Appsettings.app(new string[] { "CacheOptions", "Menukey" })); //.Where(x=>MenuIds.Contains(x.Id)).ToList(); } else { Menulist = await this._menuRepositoty.GetAll(x => x.IsDrop == false).AsNoTracking().ToListAsync(); await _redisCacheManager.Set(Appsettings.app(new string[] { "CacheOptions", "Menukey" }), Menulist); } if (!Menulist.Any()) { Menulist = await _menuRepositoty.GetAllListAsync(x => x.IsDrop == false);//根据菜单ID获取菜单列表 x=>MenuIds.Contains(x.Id) } foreach (var item in RoleAssig) { var RoleModel = Rolelist.Where(x => x.Id == item.RoleId).FirstOrDefault(); //获取角色实体 var MenuModel = Menulist.Where(x => x.Id == item.MenuId).FirstOrDefault(); //获取菜单实体 RoleModuleList.Add(new RoleActionModel { RoleName = RoleModel.Id, ActionName = MenuModel.APIAddress }); if (!item.ButtonIds.IsNullOrEmpty()) //判断是否存在按钮 { List <Guid> guids = new List <Guid>(); var btnArr = item.ButtonIds.Split(',').Select(x => x.ToGuid()).ToList(); var RoleBtn = Btnlist.Where(x => btnArr.Contains(x.Id)).ToList(); RoleModuleList.AddRange(RoleBtn.Select(x => new RoleActionModel { RoleName = RoleModel.Id,//在这里代表的是 ActionName = x.APIAddress, })); } } return(RoleModuleList); }
public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; //拦截 if (qCachingAttribute != null) { //获取自定义缓存键,和Memory内存缓存一样 var cacheKey = CustomCacheKey(invocation); //获取值(string类型)核心一 string cacheValue = _cache.GetValue(cacheKey); if (cacheValue != null) { //获取返回类型 var type = invocation.Method.ReturnType; if (type.FullName == "System.Void") { return; //如果是同步并且是voi类型,返回 } var resultTypes = type.GenericTypeArguments; //拿到泛型参数 object response; if (type != null && typeof(Task).IsAssignableFrom(type)) //异步 { //返回异步的对象Task<T>核心二 if (resultTypes.Count() > 0)//泛型的参数存在 { var resultType = resultTypes.FirstOrDefault(); dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, resultType); //把自定义key转为泛型参数同一个类型 response = Task.FromResult(temp); //然后放入response } else { //Task无返回方法,指定时间不允许重新运行 response = Task.Yield(); } } else//如果是同步的,把获取的值转为返回值类型即可 { //核心4,要进行ChangeType response = System.Convert.ChangeType(_cache.Get <object>(cacheKey), type); } invocation.ReturnValue = response; return; } invocation.Proceed();//执行方法 //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; var type = invocation.Method.ReturnType; if (type != null && typeof(Task).IsAssignableFrom(type)) { //异步拿到Task里面的result的方法 var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; //如果返回值是空 } //核心5:将获取到指定的response 和特性的缓存时间,进行set操作 _cache.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration)); } } else { //直接执行被拦截的方法 invocation.Proceed(); } }
/// <summary> /// 读取缓存 /// </summary> /// <param name="cacheKey">键</param> /// <returns></returns> public T GetCache <T>(string cacheKey) { return(_cache.Get <T>(cacheKey)); }
/// <summary> /// 添加成员 /// </summary> /// <param name="dto"></param> /// <returns></returns> public async Task <bool> PostTeamMemberAsync(AddTeamMemberDto dto, string openId) { var isAny = db.Queryable <Wx_UserInfo>().Where(a => a.OpenId == openId).Any(); var result = 0; return(await Task.Run(() => { if (isAny == false) { Wx_UserInfo userInfo = iMapper.Map <Wx_UserInfo>(dto); userInfo.ID = IdHelper.CreateGuid(); userInfo.OpenId = openId; db.Insertable(userInfo).ExecuteCommand(); } //获取邀请人的UserId bool isInviterToken = _redisCacheManager.Get(dto.InviterToken); string InviterUserId = string.Empty; if (isInviterToken) { //根据邀请人Token获取到邀请人OpenId var InviterOenId = _redisCacheManager.GetValue(dto.InviterToken).ToString().Split(";")[0].Trim('"'); InviterUserId = db.Queryable <Wx_UserInfo>().Where(a => a.OpenId == InviterOenId).First()?.ID; } var UserInfo = db.Queryable <Wx_UserInfo>().Where(a => a.OpenId == openId).Select(a => new { UserId = a.ID, MobilePhone = a.MobilePhone }).First(); //找到加入人UserId、MobilePhone var roleId = db.Queryable <Role>().Where(a => a.TeamId == dto.TeamId && a.Name == AppConsts.RoleName.Ordinary).First()?.ID; var isMember = db.Queryable <TeamMember>().Where(a => a.TeamId == dto.TeamId && a.IsDeleted == false && a.JoinedUserId == UserInfo.UserId).Any(); if (isMember) { throw new Exception("成员已经加了团队,不能再次加入!"); } else { TeamMember teamMember = iMapper.Map <TeamMember>(dto); teamMember.ID = IdHelper.CreateGuid(); teamMember.TeamNickName = dto.NickName; teamMember.IsDeleted = false; teamMember.InviterUserId = InviterUserId; teamMember.JoinedUserId = UserInfo.UserId; teamMember.RoleId = roleId; result = db.Insertable(teamMember).ExecuteCommand(); if (result > 0 && UserInfo.MobilePhone != null) { db.Updateable <TeamMember>().SetColumns(a => new TeamMember() { MobilePhone = UserInfo.MobilePhone }) .Where(a => a.ID == teamMember.ID).ExecuteCommand(); } } return result > 0; })); }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCachingAttribute != null) { //获取自定义缓存键,这个和Memory内存缓存是一样的,不细说 var cacheKey = CustomCacheKey(invocation); //核心1:注意这里和之前不同,是获取的string值,之前是object var cacheValue = Cache.GetValue(cacheKey); if (cacheValue != null) { //将当前获取到的缓存值,赋值给当前执行方法 var type = invocation.Method.ReturnType; var resultTypes = type.GenericTypeArguments; if (type.FullName == "System.Void") { return; } object response = null; if (typeof(Task).IsAssignableFrom(type)) { //返回Task<T> if (resultTypes.Any()) { var resultType = resultTypes.FirstOrDefault(); // 核心1,直接获取 dynamic 类型 dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, resultType); //dynamic temp = System.Convert.ChangeType(cacheValue, resultType); // System.Convert.ChangeType(Task.FromResult(temp), type); response = Task.FromResult(temp); } else { //Task 无返回方法 指定时间内不允许重新运行 response = Task.Yield(); } } else { //将缓存返回给调用者 if (type == typeof(SingleApiResponse)) { response = Cache.Get <SingleApiResponse>(cacheKey); } else if (type == typeof(ListApiResponse)) { response = Cache.Get <ListApiResponse>(cacheKey); } } invocation.ReturnValue = response; return; } //去执行当前的方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; //Type type = invocation.ReturnValue?.GetType(); var type = invocation.Method.ReturnType; if (type != null && typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } // 核心5:将获取到指定的response 和特性的缓存时间,进行set操作 Cache.Set(cacheKey, response, TimeSpan.FromMilliseconds(qCachingAttribute.AbsoluteExpiration)); } } else { //直接执行被拦截方法 invocation.Proceed(); } }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法特性验证 var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCachingAttribute != null) { //获取自定义缓存键,这个和Memory内存缓存是一样的 var cacheKey = CustomCacheKey(invocation); //核心1:注意这里和之前不同,是获取的string值,之前是object var cacheValue = _redisCache.GetValue(cacheKey); if (cacheValue != null) { //将当前获取到的值,赋给当前执行的方法 var type = invocation.Method.ReturnType; var resultTypes = type.GenericTypeArguments; if (type.FullName == "System.Void") { return; } object response; if (type != null && typeof(Task).IsAssignableFrom(type)) { //核心2:异步返回Task<T> if (resultTypes.Count() > 0) { var resultType = resultTypes.FirstOrDefault(); //核心3:直接序列化dynamic类型, dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, resultType); response = Task.FromResult(temp); } else { response = Task.Yield(); } } else { //核心4:要进行changeType response = System.Convert.ChangeType(_redisCache.Get <object>(cacheKey), type); } invocation.ReturnValue = response; return; } //去执行当前的方法。 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; var type = invocation.Method.ReturnType; if (type != null && typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } // 核心5:将获取到指定的response 和特性的缓存时间,进行set操作 _redisCache.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration)); } } invocation.Proceed(); }
/// <summary> /// 获取树形菜单,渲染左侧菜单使用 /// </summary> /// <returns></returns> public async Task <RouterBar> RouterBar(Guid userId) { var Rolelist = await _userRoleRepository.GetAllListAsync(x => x.UserIdOrDepId == userId); //根据用户ID获取角色列表 var RoleIds = Rolelist.Select(x => x.RoleId).ToList(); //获取到角色列表中的角色ID var MenuList = await _roleRightAssigRepository.GetAllListAsync(x => RoleIds.Contains(x.RoleId)); //根据角色Id获取菜单列表 var MenuIds = MenuList.Select(x => x.MenuId).ToList(); //获取角色权限中的菜单ID List <SysMenu> baselist = new List <SysMenu>(); if (_redisCacheManager.Get("Menu"))//判断菜单缓存是否存在,如果存在则取缓存不存在则取数据库 { baselist = _redisCacheManager.GetList <SysMenu>("Menu"); } else { RestMenuCache(); baselist = _redisCacheManager.GetList <SysMenu>("Menu"); } if (!baselist.Any()) { baselist = await _menuRepositoty.GetAllListAsync(x => MenuIds.Contains(x.Id));//根据菜单ID获取菜单列表 x=>MenuIds.Contains(x.Id) } var btnlist = await _buttonRepositoty.GetAllListAsync(x => x.IsShow == true && x.IsDrop == false); RouterBar routerbar = new RouterBar() { Id = Guid.Empty, name = "根节点", order = 0, path = "", meta = new NavigationBarMeta(), ParentId = Guid.Empty, }; //定义一个树形列表 var routerbarTreeall = baselist.Where(x => x.IsDrop == false).Select(s => new RouterBar { Id = s.Id, name = s.Name, ParentId = s.ParentId, iconCls = s.Icon, order = s.Sort, path = s.UrlAddress, meta = new NavigationBarMeta { requireAuth = true, title = s.Name, } }).ToList(); try { //递归形成前端路由器格式的树形菜单 CreateMenuTree(routerbarTreeall, routerbar, btnlist, MenuList); return(routerbar); } catch (Exception ex) { throw ex; } }
public async Task <MessageModel <string> > Login(string username, string password, string validatecode, string reid) { var res = new MessageModel <string>(); //获取用户信息 if (Convert.ToBoolean(_config.Value.isdebug) || validatecode == "YT9999") { res.data = $"{{\"access_token\":{_config.Value.defaulttoken}}}"; res.msg = "登录成功"; res.success = true; res.code = System.Net.HttpStatusCode.OK; return(res); } try { var requestid = reid; var values = _redis.Get <string>(requestid + "_ValidateCode"); if (string.IsNullOrWhiteSpace(values)) { res.data = ""; res.msg = "验证码过期"; res.code = System.Net.HttpStatusCode.RequestTimeout; res.success = false; return(res); } if (values.Equals(validatecode)) { var viewmodel = await _UserBussiness.GetUser(username, password); //todo 看不懂异步的打开这些注释,看看 //Console.WriteLine("1"); //var ASD = await _UserBussiness.GetUser(username, password); //Task.Run(() => { // for (int i =5; i < 6; i++) // { // Thread.Sleep(10000); // Console.WriteLine("-11"); // } //}); //var viewmodel= await ASD; //Console.WriteLine("-1"); if (viewmodel != null) { res.data = $"{{\"access_token\":\"{JWTHelper.IssueJwt(viewmodel)}\"}}"; res.msg = "登录成功"; res.code = System.Net.HttpStatusCode.OK; res.success = true; } else { res.data = ""; res.msg = "暂无数据"; res.code = System.Net.HttpStatusCode.OK; res.success = false; } } else { res.data = ""; res.msg = "验证码错误"; res.code = System.Net.HttpStatusCode.OK; res.success = false; } } catch (Exception e) { if (e.GetType().Name.Equals("NullReferenceException")) { res.data = ""; res.msg = "账号密码错误"; res.code = System.Net.HttpStatusCode.OK; res.success = false; } else { res.data = ""; res.msg = e.Message; res.code = System.Net.HttpStatusCode.OK; res.success = false; } } return(res); }
public async Task <object> Get(int id, int page = 1, string bcategory = "技术博文") { int intTotalCount = 6; int total; int totalCount = 1; List <BlogArticle> blogArticleList = new List <BlogArticle>(); using (MiniProfiler.Current.Step("开始加载数据:")) { try { if (_redisCacheManager.Get <object>("Redis.Blog") != null) { MiniProfiler.Current.Step("从Redis服务器中加载数据:"); blogArticleList = _redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { MiniProfiler.Current.Step("从MSSQL服务器中加载数据:"); blogArticleList = await _blogArticleServices.Query(a => a.bcategory == bcategory); _redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2)); } } catch (Exception e) { MiniProfiler.Current.CustomTiming("Errors:", e.Message); blogArticleList = await _blogArticleServices.Query(a => a.bcategory == bcategory); } } total = blogArticleList.Count(); totalCount = blogArticleList.Count() / intTotalCount; using (MiniProfiler.Current.Step("获取成功后,开始处理最终数据")) { blogArticleList = blogArticleList.OrderByDescending(d => d.bID).Skip((page - 1) * intTotalCount).Take(intTotalCount).ToList(); foreach (var item in blogArticleList) { if (!string.IsNullOrEmpty(item.bcontent)) { item.bRemark = (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Length >= 200 ? (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Substring(0, 200) : (HtmlHelper.ReplaceHtmlTag(item.bcontent)); int totalLength = 500; if (item.bcontent.Length > totalLength) { item.bcontent = item.bcontent.Substring(0, totalLength); } } } } return(Ok(new { success = true, page = page, total = total, pageCount = totalCount, data = blogArticleList })); }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCachingAttribute != null) { //获取自定义缓存键 var cacheKey = CustomCacheKey(invocation); //注意是 string 类型,方法GetValue var cacheValue = _cache.GetValue(cacheKey); if (cacheValue != null) { //将当前获取到的缓存值,赋值给当前执行方法 var type = invocation.Method.ReturnType; var resultTypes = type.GenericTypeArguments; if (type.FullName == "System.Void") { return; } object response; if (typeof(Task).IsAssignableFrom(type)) { //返回Task<T> if (resultTypes.Any()) { var resultType = resultTypes.FirstOrDefault(); // 核心1,直接获取 dynamic 类型 dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, resultType); //dynamic temp = System.Convert.ChangeType(cacheValue, resultType); // System.Convert.ChangeType(Task.FromResult(temp), type); response = Task.FromResult(temp); } else { //Task 无返回方法 指定时间内不允许重新运行 response = Task.Yield(); } } else { // 核心2,要进行 ChangeType response = Convert.ChangeType(_cache.Get <object>(cacheKey), type); } invocation.ReturnValue = response; return; } //去执行当前的方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; //Type type = invocation.ReturnValue?.GetType(); var type = invocation.Method.ReturnType; if (typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } _cache.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration)); } } else { invocation.Proceed();//直接执行被拦截方法 } }
public async Task <object> Get(int id, int page = 1, string bcategory = "技术博客", string key = "") { int inTotalCount = 6; int total; int totalCount = 1; List <BlogArticle> blogArticleList = new List <BlogArticle>(); if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) { key = ""; } using (MiniProfiler.Current.Step("开始加载数据:")) { try { if (_redisCacheManager.Get <object>("Redis.Blog") != null) { MiniProfiler.Current.Step("从Redis服务器中加载数据:"); blogArticleList = _redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { MiniProfiler.Current.Step("从MSSQL服务器中加载数据:"); blogArticleList = await _blogArticleServices.Query(a => a.bcategory == bcategory && a.IsDeleted == false); _redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2)); } } catch (Exception e) { MiniProfiler.Current.CustomTiming("Errors:", "Redis服务未启用,请开启该服务,并且请注意端口号,本项目使用的的6319," + "而且我的是没有设置密码。" + e.Message); blogArticleList = await _blogArticleServices.Query(a => a.bcategory == bcategory && a.IsDeleted == false); } } blogArticleList = blogArticleList.Where(d => (d.btitle != null && d.btitle.Contains(key)) || (d.bcontent != null && d.bcontent.Contains(key))).ToList(); total = blogArticleList.Count(); totalCount = blogArticleList.Count() / inTotalCount; using (MiniProfiler.Current.Step("开始处理最终数据")) { blogArticleList = blogArticleList.OrderByDescending(d => d.bID).Skip((page - 1) * inTotalCount).Take(inTotalCount).ToList(); foreach (var item in blogArticleList) { if (!string.IsNullOrEmpty(item.bcategory)) { item.bRemark = (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Length >= 200 ? (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Substring(0, 200) : (HtmlHelper.ReplaceHtmlTag(item.bcontent)); int totalLength = 500; if (item.bcontent.Length > totalLength) { item.bcontent = item.bcontent.Substring(0, totalLength); } } } } return(Ok(new { success = true, page, total, pageCount = totalCount, data = blogArticleList })); }
public async Task <object> Get(int id, int page = 1, string shoptype = "Online", string key = "") { int intTotalCount = 6; int total; int totalCount = 1; List <ShopInfo> shopList = new List <ShopInfo>(); if (string.IsNullOrWhiteSpace(key)) { key = ""; } using (MiniProfiler.Current.Step("开始加载数据:")) { try { if (_redisCacheManager.Get <object>("Redis.ShopInfo") != null) { MiniProfiler.Current.Step("从Redis服务器中加载数据:"); shopList = _redisCacheManager.Get <List <ShopInfo> >("Redis.ShopInfo"); } else { MiniProfiler.Current.Step("从MSSQL服务器中加载数据:"); shopList = await _shopInfoServices.Query(q => true); _redisCacheManager.Set("Redis.ShopInfo", shopList, TimeSpan.FromHours(2)); } } catch (Exception ex) { MiniProfiler.Current.CustomTiming("Errors:", "Redis服务未启用,请开启该服务,并且请注意端口号,本项目使用的的6319,而且我的是没有设置密码。" + ex.Message); shopList = await _shopInfoServices.Query(q => true); } } shopList = shopList.Where(q => (q.ShopName != null && q.ShopName.Contains(key))).ToList(); total = shopList.Count(); totalCount = shopList.Count() / intTotalCount; using (MiniProfiler.Current.Step("获取成功后,开始处理最终数据")) { shopList = shopList.OrderByDescending(d => d.Id).Skip((page - 1) * intTotalCount).Take(intTotalCount).ToList(); foreach (var item in shopList) { if (!string.IsNullOrEmpty(item.ShopAddress)) { item.ShopAddress = (HtmlHelper.ReplaceHtmlTag(item.ShopAddress)).Length >= 200 ? (HtmlHelper.ReplaceHtmlTag(item.ShopAddress)).Substring(0, 200) : (HtmlHelper.ReplaceHtmlTag(item.ShopAddress)); int totalLength = 500; if (item.ShopAddress.Length > totalLength) { item.ShopAddress = item.ShopAddress.Substring(0, totalLength); } } } } return(Ok(new { success = true, page, total, pageCount = totalCount, data = shopList })); }