Prevent multiple POST in asp.net mvc application

2019-06-25 23:25发布

问题:

How do I prevent the user from posting the same data to the action multiple times if they keep clicking the submit button?

I know in php, there is a way to prevent this multiple submission, but I do not see any for asp.net mvc. Is there any?

回答1:

You could disable the submit button using javascript. Example with jQuery:

$(function() {
    $('form').submit(function() {
        $('#idofsubmitbutton').attr('disabled', 'disabled');
    });
});

Note however that this might not be 100% reliable as for example the user could have javascript disabled or even worse: he could have malicious intents and automate HTTP POST requests.



回答2:

You're looking for the Post-Redirect-Get Strategy

Disabling the Submit button doesn't prevent F5 refreshes.



回答3:

The best practice is to implement PRG (http://en.wikipedia.org/wiki/Post/Redirect/Get) pattern, I have an old post on this subject on aspnet mvc http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx check the #13.



回答4:

This is a duplicate of this question, but I post my answer here for easy reference...

The PRG pattern will not prevent this, as the P action in it takes time (which is usually the case) and the user can submit the form again (via click or browser refresh), which will cause the PRG pattern to "fail".

Note that malicious users can also bypass all of your client side measures by running multiple http posts in quick succession.

A solution to all of the above is to check for duplicate submissions on server side using the following method, as described by myself, here.

I quote:

"If you make use of a hidden anti-forgery token in your form (as you should), you can cache the anti-forgery token on first submit and remove the token from cache if required, or expire the cached entry after set amount of time."

You will then be able to check with each request against the cache whether the specific form has been submitted and reject it if it has."