public override void OnActionExecuting(ActionExecutingContext context) { try { if (context.HttpContext.Request.Method == "POST") { foreach (var parameter in context.ActionDescriptor.Parameters) { var parameterName = parameter.Name; //获取Action方法中参数的名字 var parameterType = parameter.ParameterType; //获取Action方法中参数的类型 var pointRequest = context.ActionArguments[parameterName]; var entityHash = HashUtil.GetHash(pointRequest); if (_distributedCache.ExistAsync(entityHash).Result) { context.Result = new JsonResult( new JsonResultModel <object>() { status = false, code = HttpStatusCode.BadRequest, errorMsg = "请勿重复提交表单" }); } else { _distributedCache.SetAsync(entityHash, true, TimeSpan.FromSeconds(2)); } } } } catch (Exception ex) { _logger.LogError(ex, "DuplicateSubmissionActionFilter处理异常"); } base.OnActionExecuting(context); }
/// <summary> /// 拦截操作 /// </summary> /// <param name="invocation"></param> /// <param name="cacheAttribute"></param> private void GetCacheIntercept(IInvocation invocation, CacheableAttribute attribute) { //获取自定义缓存键 var cacheKey = string.IsNullOrWhiteSpace(attribute?.Key) ? GenerateCacheKey(invocation) : attribute.Key; var cacheValue = _cache.ExistAsync(cacheKey).Result; //判断redis中是否存在值 try { if (cacheValue) { //将当前获取到的缓存值,赋值给当前执行方法 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(); var data = _cache.GetAsync(cacheKey).Result; dynamic temp = JsonConvert.DeserializeObject(data, resultType !); response = Task.FromResult(temp); } else { //Task 无返回方法 指定时间内不允许重新运行 response = Task.Yield(); } } else { var data = _cache.GetAsync(cacheKey).Result; dynamic temp = JsonConvert.DeserializeObject(data, type); //不存task返回类型就直接用返回类型反序列化 response = System.Convert.ChangeType(temp, type); } invocation.ReturnValue = response; return; } } catch (Exception ex) { LogHelper.Error(ex, "【缓存切面:获取】"); } //去执行当前的方法 不能影响这块的正常运行 invocation.Proceed(); //存入缓存 try { 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; } if (attribute != null) { _cache.SetAsync(cacheKey, response, attribute.ExpiryTime.HasValue ? TimeSpan.FromMinutes(attribute.ExpiryTime.Value) : null); } } } catch (Exception ex) { LogHelper.Error(ex, "【缓存切面:设置】"); } }