Prevent Double Submit / Post on ASP.NET MVC page

后端 未结 6 728
悲&欢浪女
悲&欢浪女 2020-12-16 07:40

I am hoping for some feedback about the method I intend to use for preventing duplicate records in an ASP.NET MVC 4 application, and the knock on effects I have not though o

6条回答
  •  情歌与酒
    2020-12-16 08:06

    Sometimes, deal with it only on client side isn't enought. Try to gen a hash code of the form and save in cache (set an expiration date or something like that).

    the algorithm is something like:

    1- User made post

    2- Generate hash of the post

    3- Check the hash in cache

    4- Post already on cache? Throw exception

    5- Post isn't on cache? Save the new hash on cache and save post on database

    A sample:

                //verify duplicate post
                var hash = Util.Security.GetMD5Hash(String.Format("{0}{1}", topicID, text));
                if (CachedData.VerifyDoublePost(hash, Context.Cache))
                    throw new Util.Exceptions.ValidadeException("Alert! Double post detected.");
    

    The cache function could be something like that:

        public static bool VerifyDoublePost(string Hash, System.Web.Caching.Cache cache)
        {
            string key = "Post_" + Hash;
    
            if (cache[key] == null)
            {
                cache.Insert(key, true, null, DateTime.Now.AddDays(1), TimeSpan.Zero);
                return false;
            }
            else
            {
                return true;
            }
        }
    

提交回复
热议问题