Quantcast
Viewing all articles
Browse latest Browse all 20

Get FormDigest from C# using REST in SharePoint 2013

If you want to communicate with SharePoint 2013 through REST, you need to send FormDigest value with every request.
In JavaScript, it is very easy as it will always be available on SharePoint Page where your JavaScript code is executing. It is quite tricky when you need to submit REST requests from C# code as there is no such thing called FormDigest control. Following is a function to get the FormDigest control for your REST request in C#

private static string GetFormDigest(string webUrl)
{
//Validate input
if (String.IsNullOrEmpty(webUrl) || String.IsNullOrWhiteSpace(webUrl))
return String.Empty;

//Create REST Request
Uri uri = new Uri(webUrl + "/_api/contextinfo");
HttpWebRequest restRequest = (HttpWebRequest)WebRequest.Create(uri);
restRequest.Credentials = CredentialCache.DefaultCredentials;
restRequest.Method = "POST";
restRequest.ContentLength = 0;

//Retrieve Response
HttpWebResponse restResponse = (HttpWebResponse)restRequest.GetResponse();
XDocument atomDoc = XDocument.Load(restResponse.GetResponseStream());
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";

//Extract Form Digest
return atomDoc.Descendants(d + "FormDigestValue").First().Value;
}

Image may be NSFW.
Clik here to view.
Share


Viewing all articles
Browse latest Browse all 20

Trending Articles