#SharePointProblems | Koskila.net

Solutions are worthless unless shared! Antti K. Koskela's Personal Professional Blog

How to properly use SPWeb.AllowUnsafeUpdates

koskila
Reading Time 2 min
Word Count 279 words
Comments 0 comments
Rating 4 (1 votes)
View

At times you may need to allow unsafe updates for SPWeb objects in order 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 is good practice to limit the change to as small a scope as possible. This is true even though the setting 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 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 whatever value it was before your code.

This pattern enables you to always end up "resetting" the value for AllowUnsafeUpdates in the end. This will work no matter what happens in your code, as the final -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.

Comments

Interactive comments not implemented yet. Showing legacy comments migrated from WordPress.
Whitewater Magpie Ltd.
© 2025
Static Site Generation timestamp: 2025-08-26T05:15:54Z