SharePoint Security Validation and Unsafe Updates

By | December 18, 2008

Seeing this? The security validation for this page is invalid. I am sure this error has good intentions, but it is showing its face far too often. Hristo Pavlov has written a good explanation on AllowUnsafeUpdates here.

If you read my previous post and are attempting to update list items as the System User, you will likely run into this problem.  Setting AllowUnsafeUpdates to true for the duration of the update has allowed me to get around this exception.  Here is the helper method I am using to accomplish this:

        public static void DoUnsafeUpdate(SPWeb web, Action action)
        {
            bool allowUnsafeUpdates = web.AllowUnsafeUpdates;
            web.AllowUnsafeUpdates = true;
            action();
            web.AllowUnsafeUpdates = allowUnsafeUpdates;
        }

Couple this with the helper methods in my previous post, and you now can do both together:

        public static void DoUnsafeUpdateAsSystemUser(SPWeb web, SPWebAction action)
        {
            DoAsSystemUser(web, delegate(SPWeb systemWeb)
            {
                DoUnsafeUpdate(systemWeb, delegate()
                {
                    action(systemWeb);
                });
            });
        }

Leave a Reply

Your email address will not be published. Required fields are marked *