一、添加过滤器
/// <summary> /// 重复提交 /// </summary> public class ReSubmitAttribute : ActionFilterAttribute { /// <summary> /// 操作成功提示消息 /// </summary> public string SuccessMsg = null; /// <summary> /// 方法执行前的拦截方法 /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.Request.Method == HttpMethod.Post) { string reValue = HttpContext.Current.Request.Form["ReFlag"]; if (string.IsNullOrEmpty(reValue)) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, BaseResult.GetError("提交数据中必须包含防重提交标识"), "application/json"); return; } string cacheName = RedisHelper.GetCacheName(RedisCacheType.ReSubmit, reValue); string cacheValue = CacheManager.GetCache(cacheName); string submitValue = actionContext.ActionArguments.Count > 0 ? MD5Helper.MD5Encrypt32(SerializeHelper.ToJson(actionContext.ActionArguments)) : "0"; if (string.IsNullOrEmpty(cacheValue) || cacheValue.Equals(submitValue) == false) { CacheManager.SetCache(cacheName, submitValue, TimeSpan.FromMinutes(1), Tools.Cache.Redis.ExpirType.Absolute); return; } if (cacheValue.Equals(submitValue)) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, BaseResult.GetSuccess(string.IsNullOrEmpty(SuccessMsg) ? "操作成功" : SuccessMsg), "application/json"); return; } } } /// <summary> /// 删除重复提交标识 /// </summary> public static void RemoveReFlagCache() { string reValue = HttpContext.Current.Request.Form["ReFlag"]; if (string.IsNullOrEmpty(reValue) == false) { string cacheName = RedisHelper.GetCacheName(RedisCacheType.ReSubmit, reValue); CacheManager.RemoveCache(cacheName); } } }
二、添加实体基类
/// <summary> /// 防重提交实体 /// </summary> public abstract class ReSubmitModel { /// <summary> /// 防重提交标识 /// </summary> [Ignore] public Guid ReFlag { get; set; } = Guid.NewGuid(); }
三、将返回实体类继承ReSubmitModel
标签:WebApi,string,actionContext,cacheName,提交,防重,Net,public,reValue From: https://www.cnblogs.com/5tomorrow/p/17613271.html