Once my colleague was getting an error “The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again” while trying to move documents from one document library to another document library.

His piece of code was,

public void MoveDocument(string filePath,string destinationList)
{
try
{
SPWeb ospWeb = SPContext.Current.Web;
SPList destList = ospWeb.Lists[destinationList];
SPFile ospFile = ospWeb.GetFile(filePath);
ospFile.MoveTo(ospWeb.Url + "/" + destList.RootFolder + "/" + ospFile.Name);
}
catch (Exception ex)
{
throw ex;
}
}

After some amount of searching in the net, it was found that the error is caused due the security validation in sharepoint. So, there should be a method we turn  off the security validation:

One method to turn off security validation is,
Central Administration—>application management—->web application general settings–>”turn security validation off”

but,it is dangerous to do….as it could potentially leave your site open to malicious code.

Ideally, the security validation should be turned off only long enough for your own code to execute and should be turned back on again as soon as the code finishes execution.

So, the code needs to be recoded as,
public void MoveDocument(string filePath,string destinationList)
{
try
{
SPWeb ospWeb = SPContext.Current.Web;
Microsoft.SharePoint.Administration.SPWebApplication webApp = ospWeb.Site.WebApplication;
webApp.FormDigestSettings.Enabled = false;
SPList destList = ospWeb.Lists[destinationList];
SPFile ospFile = ospWeb.GetFile(filePath);
ospFile.MoveTo(ospWeb.Url + “/” + destList.RootFolder + “/” + ospFile.Name);
webApp.FormDigestSettings.Enabled = true;
}
catch (Exception ex)
{
throw ex;
}
}

Advertisements