Cookies missing on XForm submission
I came across a nasty little gotcha when working with XForms recently and although I grant it is somewhat of an edge case the cause is a bit obscure so I though it worth blogging about in case anyone else happens across it. The cause will also have other side effects that haven’t affected me but might get you! So, what’s the problem? If you send an XForm to a custom URL (quite a common scenario when storing your XForm submitted data in somewhere other than the standard EPiServer storage) then if you need to pull any information from the HTTP Request headers you may find it missing or incorrect, including cookies. If you check the request on form submission with Fiddler you’ll see all the request data including cookies there, but by the time your page/controller which handles the submission is called, it’s all disappeared or changed.
The reason for this is that the actual request from the browser is not the HTTP Post to your handler page/controller. It’s a postback to the server, which then prepares the XForm submission and make a SECOND call to your handler. This second call does not pull the request headers and cookies across from the initial call, and so you’ll find them missing. (Side note – be aware that when sending to a custom page, you need a full URL for this very reason. A relative URL will not work.) In my particular case I needed a cookie setting from the page, but by the time my handler was called it was of course missing.
There are different ways to solve this. In my case I was only concerned with one particular value and so the easiest thing was to intercept the BeforeSubmitPostedData event of the XForm Control (you can put this in an initializable module) and manipulate my URL to add the value I needed to it. At this point I’m still in the ‘first call’ and so I have my cookies – I could simply pull out my value and inject it into my second request in the way I wanted to. If your handler has the SaveFormDataEventArgs called ‘e’ then you’ll find the URL that you need to change in e.FormData.CustomUrl. You could manipulate the URL to inject a URL segment with your value which matches a custom route – ideal if sending to an MVC controller which is what I was doing – or you could add a querystring value which is probably better if you are sending to a WebForm.
I hope that if anyone else comes across a related problem with XForm submission to a custom URL, this little post can help them out!