Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What methods are available to stop multiple postbacks of a form in ASP.NET MVC?

A common web problem is where a user clicks the submit button of a form multiple times so the server processes the form more than once. This can also happen when a user hits the back button having submitted a form and so it gets processed again.

What is the best way of stopping this from happening in ASP.NET MVC?

Possibilities as I see it are:

  1. Disable the button after submit - this gets round the multiple clicks but not the navigation
  2. Have the receiving action redirect immediately - browsers seem to leave these redirects out of the history
  3. Place a unique token in the session and on the form - if they match process the form - if not clear the form for a fresh submit

Are there more?

Are there some specific implementations of any of these?

I can see the third option being implemented as an ActionFilter with a HtmlHelper extension in a similar manner to the anti-forgery stuff.

Looking forward to hearing from you MVC'ers out there.

like image 556
WooWaaBob Avatar asked May 20 '09 16:05

WooWaaBob


2 Answers

Often people overlook the most conventional way to handle this which is to use nonce keys.

You can use PRG as others have mentioned but the downside with PRG is that it doesn't solve the double-click problem, it requires an extra trip to the server for the redirect, and since the last step is a GET request you don't have direct access to the data that was just posted (though it could be passed as a query param or maintained on the server side).

I like the Javascript solution because it works most of the time.

Nonce keys however, work all the time. The nonce key is a random unique GUID generated by the server (also saved in the database) and embedded in the form. When the user POSTs the form, the nonce key also gets posted. As soon as a POST comes in to the server, the server verifies the nonce key exists in its database. If it does, the server deletes the key from the database and processes the form. Consequently if the user POSTs twice, the second POST won't be processed because the nonce key was deleted after processing the first POST.

The nonce key has an added advantage in that it brings additional security by preventing replay attacks (a man in the middle sniffs your HTTP request and then replays it to the server which treats it as a legitimate).

like image 197
aleemb Avatar answered Nov 05 '22 20:11

aleemb


You should always return a redirect as the HTTP response to a POST. This will prevent the POST from occuring again when the user navigates back and forth with the Forward/Back buttons in the browser.

If you are worried about users double-clicking your submit buttons, just have a small script disable them immediately on submit.

like image 5
mookid8000 Avatar answered Nov 05 '22 20:11

mookid8000