Get FormDigest from C# using REST in SharePoint 2013

By Namwar Rizvi - Last updated: Sunday, March 17, 2013 - Save & Share - 2 Comments

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
Posted in C#, Code, SharePoint 2013 • Tags: , , Top Of Page

2 Responses to “Get FormDigest from C# using REST in SharePoint 2013”

Comment from Nick M
Time March 27, 2013 at 12:40 am

You probably want to dispose that httpwebresponse…

Comment from Rohit.Doc
Time April 20, 2013 at 7:02 am

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?

Write a comment