Search This Blog

Wednesday, 30 May 2012

The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again


In SharePoint above exception is very common. Mentioned below are the causes of this exception
  1. Trying to update Sharepoint object Like SPSite, SPWeb etc on GET request. Actaully SharePoint doesn̢۪t allow us to update SharePoint object in Get request to avoid cross-site scripting.
  2. While post request also you may encounter above exception. Let me share few real-time scenario:
·         If user having read/write permission on few list tries to update Security Groups or try to add new user into SharePoint site. Even if you put your code block inside SPSecurity.RunWithElevatedPrivileges, you might get same exception.
                  Sample Code:
          SPSecurity
.RunWithElevatedPrivileges(delegate()
          {
                using (SPSite oSite = new SPSite( SPContext.Current.Site.ID))
                {
                        using (SPWeb oWeb= oSite.OpenWeb())
                        {
                                SPUser oUser = oWeb.EnsureUser(LoginName);
                        }
                 }
});
·         We show popup using window.open method and if there is logic to update SPWeb , SPSite etc object in the code behind, you might encounter same exception.
Solution:
If you still want to allow updates to the database as a result of a GET request or without requiring a security validation, set "AllowUnsafeUpdates" of SPWeb or SPSite to true. But be careful while using this property always reset "AllowUnsafeUpdates" to false after unsafe update.

Sample Code:
SPWeb oWeb;
try
{
   using (
SPSite oSite = new SPSite(SPContext.Current.Site.ID))

   {
       using(oWeb = oSite.OpenWeb())

       {
                  oWeb.AllowUnsafeUpdates =
true;
                  // write Code
       }
   }
}

catch ( Exception ex)
{
      //Log Exception
}

finally

{
      oWeb.AllowUnsafeUpdates =
false;
}


No comments:

Post a Comment