"The security validation for this page is invalid" error when updating objects through SharePoint object model
This error is often encountered when SharePoint OM is used to update site/web/list objects from within a web context. Some thing so basic as the code below could fail:
using (SPSite site = new SPSite("https://moss"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["List1"];
list.Title = "List2";
list.Update();
web.Update();
}
}
Setting the "AllowUnsafeUpdates" properties of both the SPSite and SPWeb objects to "true", mostly will resolve this issue out if you are using a code similar to above within a webpart or an ASP.NET web application. When you are running from the context of a separate web application make sure the application pool identity running your ASP.NET web application is the same as the one that's running SharePoint's site. Below is a code that fixes the "security validation for this page is invalid" error.
using (SPSite site = new SPSite("https://moss"))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists["List1"];
list.Title = "List2";
list.Update();
web.Update();
}
}
Thought we might actually prevent some support calls by posting this :)