SharePoint Start Workflow : Error The security validation for this page is invalid.

Whenever we start the workflow programmatically using SPWorkflowManager.StartWorkflow(), it throws security validation exception. Since we run with elevated previleges, the way to fix is to call SPUtility.ValidateFormDigest(). I am assuming you will get the ListItem by using GetSPListItem().

 

var item = GetSPListItem()

if (item != null)
                        {
                            SPWeb web = item.Web;
                            SPWorkflowManager workflowManager = item.Web.Site.WorkflowManager;
                            var wfa = (from SPWorkflowAssociation spwfa in item.ParentList.WorkflowAssociations
                                       where
                                           spwfa.Name == UserProfileConstants.UserProfileApprovalWorkflow
                                           && spwfa.Enabled == true
                                       select spwfa).FirstOrDefault();

                            if (wfa != null)
                            {
                                try
                                {
                                    SPUtility.ValidateFormDigest();
                                    web.AllowUnsafeUpdates = true;
                                    SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        workflowManager.StartWorkflow(item, wfa, wfa.AssociationData, true);
                                    });
                                }
                                catch (Exception ex)
                                {
                                    item.Delete();
                                    throw;
                                }
                                finally
                                {
                                    web.AllowUnsafeUpdates = false;
                                }                                
                            }
                            else
                            {
                                item.Delete();
                                this.DisplayErrorMessage("No Active workflows found.");
                            }
                        }