I have code like this to conditionally create a Sharepoint list (sort of an upsert):
private void ConditionallyCreateList()
{
SPWeb site = SPContext.Current.Web;
// Check to see if list already exists; if so, exit
if (site.Lists.TryGetList(listTitle) != null) return;
SPListCollection lists = site.Lists;
SPListTemplateType listTemplateType = new SPListTemplateType();
listTemplateType = SPListTemplateType.GenericList;
string listDescription = "This list retains vals inputted for the Post Travel form";
Guid ListId = lists.Add(listTitle, listDescription, listTemplateType);
. . .
This worked when first creating, and on subsequent execustions of the app.
However, I made some radical refactorings to the list structure and deleted the old one, so that (I hoped) a new one with the new structure would be created. However, instead of getting a refactored list, I got this on the last line shown above:
Microsoft.SharePoint.SPException was unhandled by user code
Message=Updates are currently disallowed on GET requests. To allow updates on a GET, set the 'AllowUnsafeUpdates' property on SPWeb.
I was able to resolve this by adding the indicated code:
site.AllowUnsafeUpdates = true;
...but why is this necessary? Why is the creation of a list which should no longer exist (I deleted it from the Sharepoint "All Site Content" bazaar) problematic (potentially an 'unsafe update')?
In an effort to protect itself from things like XSS and session hijacking, most updates to a SharePoint site are tied to a form digest control embedded on the same page from which the user makes the change. If the information from that form digest control isn't present when an update is triggered, SharePoint assumes the worst. This is especially important in cases where server-side code might execute with elevated privileges.
As you discovered, this is easily avoidable by switching the SPWeb object's AllowUnsafeUpdates
property to true
immediately before making any change.