How to prevent duplicate form submission in ASP.NE

2019-04-13 17:36发布

问题:

I have a razor view that renders a html form and it posts to the server. If the form values are right then it gets saved to database. After insertion, I redirect to another view where user can make further changes.

Right now the user can hit browser back button and resubmit the form to create another record in db.

How do I prevent duplicate submission in my MVC app?

回答1:

One solution is to put a hidden "token" field on the form that's generated randomly when the form loads. When you see that token come back on creation store it somewhere temporarily (in session if you're using sessions for example). If you see the same one again, you can assume the same form was submitted twice quickly together.



回答2:

Create a cookie to represent that particular page when it succeeds. If it is replayed with the cookie (which the browser would now send over with every request) you know not to allow the new attempt.



回答3:

Redirect the user to another HttpGet action after handling the post request. So that when the user refreshes the browser the post action will not be called again.

return RedirectToAction("YourActionMethod");



回答4:

Although client side validation is possible, it is not secure enough. I am not sure if this method applies to MVC 3, but what i did is implement a ActionFilterAttribute

here is the implementation:

 public class PreventFrequentCallsAttribute : ActionFilterAttribute
 {
    public int DelayRequest = 5;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
            var request = filterContext.HttpContext.Request;      
            var cache = filterContext.HttpContext.Cache;

            var originationInfo = request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? request.UserHostAddress;
            originationInfo += request.UserAgent;
            var targetInfo = request.RawUrl + request.QueryString;
            var hashValue = string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(originationInfo + targetInfo)).Select(s => s.ToString("x2")));

            if (cache[hashValue] != null)
            {    
                filterContext.Controller.ViewData.ModelState.AddModelError("ExcessiveRequests", "Excessive Request Attempts Detected.");                    
            }
            else
            {
                cache.Add(hashValue, originationInfo, null, DateTime.Now.AddSeconds(DelayRequest), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            }

            base.OnActionExecuting(filterContext);
    }
}

later, in the target controller, just add this attribute:

    [PreventFrequentCalls(3)]
    public PartialViewResult LogOn(LogOnViewModel model)