This post was most recently updated on September 30th, 2022.
2 min read.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.
- How to solve keyboard shortcuts not working in Google Chrome on Windows? - September 10, 2024
- Search (and secretly, sync) broken in OneNote? A quick fix! - September 3, 2024
- “Destination Path Too Long” when copying files in File Explorer? Easy workaround(s)! - August 27, 2024