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;
}
Share

2 thoughts on “Get FormDigest from C# using REST in SharePoint 2013”

  1. Hi,
    I have not worked on Sharepoint before. I am more Asp.net web developer. My client is planning to move all new web application development to Sharepoint 2010. My question is it better to build web application as a stand alone web application or build it inside Sharepoint? If I were to build it with Sharepoint what are things that I need to know before I could build on top sharepoint?

Comments are closed.

Share via
Copy link
Powered by Social Snap