SharePoint2013

How to properly use SPWeb.AllowUnsafeUpdates?

At times you may need to allow unsafe updates for SPWeb objects to get your code to run. This, in SharePoint’s C# full-trust code, is done by setting SPWeb.AllowUnsafeUpdates to true.

However, as this is an exception to security settings, you should generally avoid it. When you can’t, it’s a good practice to limit the change to as small a scope as possible. This is true even though the setting is only persisted for the duration of the request (unless the SPWeb object was gotten from SPSite.GetWeb() or SPSite.Webs[]).

Enabling AllowUnsafeUpdates for an SPWeb object

I’ve found the easiest way to temporarily allow unsafe updates in a safe way but without too much of extra code to be using a try-(catch-)finally -block. You’ll start by allowing unsafe updates, run your code, and finally set the unsafe updates to be whatever value it was before your code.

This pattern enables you to always end up “resetting” the value for AllowUnsafeUpdates in the end. This’ll work no matter what happens in your code, as the finally -block is always run. 

using (SPWeb web = someWayToGetSPWebObject()) {
 bool allowUnsafeUpdate = web.AllowUnsafeUpdates;
 try {
  web.AllowUnsafeUpdates = true;
  // your unsafe code here
 }
 // you might want to add a catch -block, depending on your code
 finally {
  web.AllowUnsafeUpdates = allowUnsafeUpdate;
 }
}

Note:

Please note, that it’s unwise to simply set the AllowUnsafeUpdates to false after your code has run. There’s an ever-so-slight chance of it screwing up some other code running in the same context at the same time!

And of course, it’s likely to be unwise to allow unsafe updates if you’re handling data that was gotten as user input.

The following two tabs change content below.

Antti K. Koskela

Solutions Architect / Escalations Engineer at Koskila / Norppandalotti Software / Valo Solutions
Antti Koskela is a proud digital native nomadic millenial full stack developer (is that enough funny buzzwords? That's definitely enough funny buzzwords!), who works as a Solutions Architect for Valo Intranet, the product that will make you fall in love with your intranet. Working with the global partner network, he's responsible for the success of Valo deployments happening all around the world. He's been a developer from 2004 (starting with PHP and Java), and he's been bending and twisting SharePoint into different shapes since MOSS. Nowadays he's not only working on SharePoint, but also on .NET projects, Azure, Office 365 and a lot of other stuff. This is his personal professional (e.g. professional, but definitely personal) blog.

Let me know your thoughts!