While spending some time working with content types recently I have encountered the following error more times than I care to mention:
The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.
This error has plagued me throughout my content type endeavours and continued to be displayed intermittently despite having searched the web and attempted the numerous approaches suggested (i.e. SPSecurity.RunWithElevatedPrivileges(), .AllowUnsafeUpdates = true & .FormDigestSettings.Enabled = false).
Having spent time looking deeper into this it appears that there was one technique I had failed to try and wouldn’t you just know it, this one (has so far) appeared to solve all my security problems.
If you are reading this then you are no doubt aware that for security reasons SharePoint protects the database by preventing a web application from updating unless it has passed security validation. All of the approaches mentioned above go some way towards this but the best way to update site data is to add a page directive and FormDigest control directly to the aspx form.
This can be done as follows:
Add page directive to top of aspx page:
<%@ Register Tagprefix=”SharePoint” Namespace=”Microsoft.SharePoint.WebControls” Assembly=”Microsoft.SharePoint, Version=188.8.131.52, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
Add FormDigest control within form tags:
<form id=”Form1″ method=”post” runat=”server”>
<SharePoint:FormDigest ID=”spFormDigestControl” runat=”server”/>
With the above in place I was able to dispense with the .RunWithElevatedPrivileges anonymous method I had wrapped around my update code (in fact I had to or it continued to throw the same error error!).
This has certainly done the trick for me, but it took a little bit of trial and error before I managed to find it.