What is a double POST
So I have been developing websites since I was sixteen, even started my own business back then and wrote a PHP backend for notifications and newsletter type stuff. Back then you used CGI primarily to do these things and access the mail client on the server hosting your website. Another thing I remember back in the day is having to deal with the possibility of having a double POST. A double post is when someone is posting to a form on your site (contact form, shopping cart etc..) and after the post, refreshes the page, causing yet another POST. If handled incorrectly, this POST could possibly reek havoc on your data and skew the reporting on the data. Even more importantly, if handled improperly on a shopping card, the customer can get charged twice for one transaction. Below is a picture I grabbed off of Wikipedia.
You will notice that once the user tries to refresh the page, it takes the same exact path the original submit did. This happens when the page you land on after the submission is just sent back as part of the body of the HTTP status code 200 OK because the browsers cache holds on to your previous action and during refresh, does that last action. To see all the various HTTP status codes and understand there use, here is a link to a better understanding.The success page was part of the 200 return from the server, so there is nothing else for the browser to do. The browser is actually doing what it was designed to do.
The solution (PRG)
So how does one solve this conundrum? Well, interestingly enough, like most things in software design and as Steve Jobs would say if he was still alive “There’s a pattern for that!”. The pattern, is Post Redirect Get, also known as PRG for short. PRG uses the 3xx series HTML codes to solve these issues by redirecting (this is what the 300 series codes are designed for) the browser to another page thus causing a new GET to occur on the browser. below is an image of what this would look like.
Now, when this happens, now the browsers cache is filled with the GET and NOT the POST. Pretty neato huh? What’s even cooler is that .NET MVC provides tools to do this easily like RedirectToAction. A post that I found well thought out was here, where Jorrit explains how to use not only the RedirectToAction, but how to use TempData to persist the information collected on the screen to the redirected option. TempData is more lightweight and doesn’t need to be disposed of like Session objects do making it ideal for the MVC architecture with attempts to persist less data and be as stateless as possible.
On another post, I will go over how to use TempData and persist it, but for now, if you would like to learn more about it, see the link above. I hope you enjoyed my explanation on PRG and if you didn’t before, have a better understanding of it now.