For REST operations in C# I recommend you to use extremely useful library called RestSharp
(more than 1M downloads for last year).
So you need to install it first from nuget:
Install-Package RestSharp
Then you need to create your credentials object, for example in a following way:
var passWord = new SecureString();
foreach (char c in "mypass") passWord.AppendChar(c);
var creds = new SharePointOnlineCredentials("[email protected]", passWord);
var baseUrl = "https://sp.sharepoint.com/sites/dev/";
Now if you need to get all list items:
var resultJSON = GetItems(creds, baseUrl);
And GetItems method:
private static string GetItems(SharePointOnlineCredentials creds, string baseUrl)
{
var client = new RestClient(baseUrl + "_api/");
var getItemsRequest = new RestRequest("web/lists/getbytitle('coolist')/items", Method.GET);
getItemsRequest.AddHeader("Accept", "application/json");
//authentication cookie
client.CookieContainer = new CookieContainer();
client.CookieContainer.SetCookies(new Uri(baseUrl), creds.GetAuthenticationCookie(new Uri(baseUrl)));
//return just JSON string, but you can deserialize to strongly type object with
//client.Execute<MyClass>(getItemsRequest)
return client.Execute(getItemsRequest).Content;
}
For POST you need x-requestdigest
first:
var digest = GetRequestDigest(creds, baseUrl);
resultJSON = CreateItem(creds, baseUrl, digest["FormDigestValue"]);
GetRequestDigest
and CreateItem
:
private static dynamic GetRequestDigest(SharePointOnlineCredentials creds, string baseUrl)
{
var client = new RestClient(baseUrl + "_api/");
var digestRequest = new RestRequest("contextinfo", Method.POST);
digestRequest.AddHeader("Accept", "application/json");
//authentication cookie
client.CookieContainer = new CookieContainer();
client.CookieContainer.SetCookies(new Uri(baseUrl), creds.GetAuthenticationCookie(new Uri(baseUrl)));
//I'm using dynamic jsut for demo, it's better to use some strongly typed class
return client.Execute<dynamic>(digestRequest).Data;
}
private static string CreateItem(SharePointOnlineCredentials creds, string baseUrl, string digest)
{
var client = new RestClient(baseUrl + "_api/");
var createItemRequest = new RestRequest("web/lists/getbytitle('coolist')/items", Method.POST);
//createItemRequest.Parameters.Clear();
createItemRequest.AddHeader("Accept", "application/json");
createItemRequest.AddHeader("Content-Type", "application/json;odata=verbose");
//NOTE - digest added here
createItemRequest.AddHeader("X-RequestDigest", digest);
//authentication cookie
client.CookieContainer = new CookieContainer();
client.CookieContainer.SetCookies(new Uri(baseUrl), creds.GetAuthenticationCookie(new Uri(baseUrl)));
//add body with item metdata, you can use javascript serialization if you want
createItemRequest.AddParameter("application/json;odata=verbose", "{ '__metadata': { 'type': 'SP.Data.CoolistListItem' }, 'Title': 'TESTTESTS'}", ParameterType.RequestBody);
return client.Execute(createItemRequest).Content;
}