AVOID SECURITY VALIDATION ERROR HANDLING AJAX POST CALLS IN SHAREPOINT 2010

If you have an AJAX call in a SharePoint application that use the method POST to send some form data, and handling such call server side you have to modify a SharePoint** item**, probably you will come across the following security validation error:

System.Exception: Microsoft.SharePoint.SPException: The security      validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.

In order to avoid such error you should add the request digest of your form (see here for more details) in the HTTP header of the AJAX message:

    let formDigest = $("[name='__REQUESTDIGEST']").val();
            let config = {
                headers: {'X-RequestDigest': formDigest}
            };
            //console.info(formDigest);
            //return false;
            //1.RFQ save successfully
            //2.Start WF
            axios.post(serviceUrl,{
                model:JSON.stringify(ms.rfqObj)
            },config)
            .then(function(response){
                let type = response.data == "FAIL" ? "error" : "success"
                let message = response.data == "FAIL" ? "Submit failed" : "Submit successfully"
                rfq.$message({
                    message: message,
                    type: type,
                    duration:1500
                });
                act.fullscreenLoading = false;
            })
            .catch(function(error){
                act.fullscreenLoading = false;
            });

While server side you must validate such digest:

    using (SPWeb web = site.OpenWeb(webUrl))
                {
                    if (SPUtility.ValidateFormDigest())
                    {
                        SPList list = web.Lists.TryGetList(listName);
                        if (list != null)
                        {
                            web.AllowUnsafeUpdates = true;
                            SPListItem listItem = list.Items.Add();
                            foreach (KeyValuePair dic in dicListItem)
                            {
                                listItem[dic.Key] = dic.Value;
                            }
                            listItem.Update();

                            NintexWorkflowWS nws = new NintexWorkflowWS();
                            workFlowInstanceId = nws.StartWorkflowOnListItem(listItem.ID, listName, workflowName, associateData);
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                }

你可能感兴趣的:(AVOID SECURITY VALIDATION ERROR HANDLING AJAX POST CALLS IN SHAREPOINT 2010)