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

During my SharePoint project i need to clean up the site for better performance.  So first thing i started to delete the closed web parts from web part pages. As there were so many web part pages in the application so i decide to write a web application that can delete the closed web parts after run. Well when i run the application i got “The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.” error  on delete operations. I knew that this error was due to the fact that Web Page Security Validation was turned on that site and it was restricting me to delete the web part from my application. I can change the settings from Central Administration by turning off the security validation for that site but it’s not a good practices as any malicious code can harm your site as the security validation was off for that site. So i decide to handle this thing pro grammatically from my code so that it only disable security validation of web for a moment when only my code will run otherwise it will be on and protect my web from harmful activities. Well so here is the solution i applied.

Microsoft.SharePoint.Administration.SPWebApplication webApp = web.Site.WebApplication;
webApp.FormDigestSettings.Enabled = false;

// Insert your code for adding/deleting/updating here

webApp.FormDigestSettings.Enabled = true;

That’s it and i was back for deleting closed web parts 🙂