首页 > Windows开发 > 详细

webapi 重复提交问题

时间:2019-03-07 19:20:47      阅读:713      评论:0      收藏:0      [点我收藏+]

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);
}

webapi 重复提交问题

原文:https://www.cnblogs.com/zinan/p/10491336.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!