Monday, June 3, 2013

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("http://hydpc1129"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["ConfigList"];
        list.Title = "Admin";
        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("http://hydpc1129"))
{
    site.AllowUnsafeUpdates = true;
    using (SPWeb web = site.OpenWeb())
    {
        web.AllowUnsafeUpdates = true;
        SPList list = web.Lists["ConfigList"];
        list.Title = "Admin";
        list.Update();
        web.Update();
    }
}

No comments:

Post a Comment