Asp.Net WebApi防重提交
一、添加过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | /// <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); } } } |
二、添加实体基类
1 2 3 4 5 6 7 8 9 10 11 | /// <summary> /// 防重提交实体 /// </summary> public abstract class ReSubmitModel { /// <summary> /// 防重提交标识 /// </summary> [Ignore] public Guid ReFlag { get ; set ; } = Guid.NewGuid(); } |
三、将返回实体类继承ReSubmitModel
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码