zoukankan      html  css  js  c++  java
  • webapi 重复提交问题

    https://izen.live/Blog/info/13.html

    /// <summary>
    /// action方法过滤器
    /// </summary>
    public class PlatformActionFilter : Attribute, IActionFilter
    {
        private static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
        public const string hiddenToken = "hiddenToken";
        private ILog _log;
    
        public PlatformActionFilter()
        {
            this._log = LogManager.GetLogger(Startup.Repository.Name, typeof(PlatformActionFilter));
        }
    
        public void OnActionExecuted(ActionExecutedContext context)
        {
    
        }
        /// <summary>
        /// action 执行之前
        /// </summary>
        /// <param name="context"></param>
        public virtual void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string httpMethod = WebUtility.HtmlEncode(filterContext.HttpContext.Request.Method);
            if (httpMethod == "POST")
            {
                //使用请求路径作为唯一key
                string path = filterContext.HttpContext.Request.Path;
                string cacheToken = $"{hiddenToken}_{path}";
                string keyValue = new Guid().ToString() + DateTime.Now.Ticks;
    
                if (path != null)
                {
                    //var cache = iZen.Utils.Core.iCache.CacheManager.GetCacheValue(cacheToken);
                    var cv = cache.Get(cacheToken);
                    if (cv == null)
                    {
                        //iZen.Utils.Core.iCache.CacheManager.SetChacheValueSeconds(cacheToken, keyValue, 1);
                        //设置缓存1秒过期
                        cache.Set(cacheToken, keyValue, new MemoryCacheEntryOptions() { SlidingExpiration = TimeSpan.FromSeconds(1) });
                        _log.Info($"提交成功");
                    }
                    else
                    {
                        _log.Error($"{filterContext.HttpContext.Request.Method},请不要重复提交");
                        //设置了 filterContext.Result 表示返回过滤失败的结果
                        //filterContext.Result = new BadRequestObjectResult(filterContext.ModelState);
                        filterContext.Result = new BadRequestObjectResult("请不要重复提交");
                    }
    
                }
                return;
            }
            this.OnActionExecuting(filterContext);
        }
    
    }
    

    action上添加过滤器特性

    /// <summary>
    /// 测试重复提交过滤器
    /// </summary>
    /// <returns></returns>
    [PlatformActionFilter]
    [HttpPost]
    public JsonResult TestPost()
    {
        var result = new ResultModel() { IsSuccess = true, Info = "测试重复提交" };
        return Json(result);
    }
  • 相关阅读:
    Laravel 中使用支付宝、银联支付、微信支付进行支付
    C# 文件读写系列三
    C# 文件读写系列二
    C# Encoding
    C# 文件操作系列一
    Unity 依赖注入
    控制反转和依赖注入模式
    Aop学习笔记系列一
    C# lambda表达式
    C# 委托基础
  • 原文地址:https://www.cnblogs.com/zinan/p/10491336.html
Copyright © 2011-2022 走看看