RunWithUnsafeUpdates

Sometimes when you run code like this:

using (SPWeb web = site.OpenWeb())
{

web.AllowUnsafeUpdates = true;

// do stuff
web.AllowUnsafeUpdates = false;
}

you will get an exception like so:
System.Exception: Microsoft.SharePoint.SPException:
The security validation for this page is invalid. Click Back in your Web browser,
refresh the page, and try your operation again.”

This can happen especially if you use this kind of code in a loop where you´ll re-use the web or somehow that web object gets its AllowUnsafeUpdates back to false somewhere else in the code. More about this can be read here:
http://hristopavlov.wordpress.com/2008/05/16/what-you-need-to-know-about-allowunsafeupdates/

So one solution is to use an extension method where you restore the original value of AllowUnsafeUpdates back to what it was when you entered the method. I think this is kind of best practice also. So…

Extension method

public static void RunWithUnsafeUpdates(this SPWeb web, Action<SPWeb> action)
{
bool beforeState = web.AllowUnsafeUpdates;
try
{
if (web.AllowUnsafeUpdates == false)
{
web.AllowUnsafeUpdates = true;
}

action(web);
}
finally
{
web.AllowUnsafeUpdates = beforeState;
}
}

…and here is an example of how to use that code:

web.RunWithUnsafeUpdates(UnSafe =>
    {
        // do stuff that needs AllowUnsafeUpdates set to true
    }

UPDATE 2010-02-20: The code for this extension method and others can now be found on codeplex.

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: