"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://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(“http://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 🙂

Comments (6)

  1. anonymou says:

    How can i add this code in masterpage

  2. Charles Lee says:

    I have just recently written a post with more info on this error.

    http://www.simple-talk.com/community/blogs/charleslee/archive/2010/01/05/85440.aspx

  3. Dinesh Bagne says:

    Thanks…..very sweet and short solution.

  4. Bhushan says:

    hey..

    nice article..

    but yes one more check need to be done ..

    verify whether you have FormDigest control added on page from which request is sent .. 🙂

  5. Optimist says:

    Obviously Bhushan did the application development exam 😉

    Question should be why you want to bypass a security validation. This is a bypass of security not a fix imo