In order to consume SharePoint REST service using .NET you could consider the following approaches:
- HttpClient - Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. (
.NET Framework 4.5
)
- WebClient - provides common methods for sending data to and receiving data from a resource identified by a URI. (
.NET Framework 1.1
)
- HttpWebRequest - provides an HTTP-specific implementation of the WebRequest class, more low-level then the previous ones
All of them allows to perform CRUD operations in SharePoint Online.
About SharePoint Online authentication
Since SharePoint Online (SPO) uses claims based authentication, you could consider the following options:
Example
The following example demonstrate how to retrieve List using WebClient:
public static JToken GetList(Uri webUri, ICredentials credentials,string listTitle)
{
using (var client = new WebClient())
{
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Credentials = credentials;
client.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
var endpointUri = new Uri(webUri, string.Format("/_api/web/lists/getbytitle('{0}')", listTitle));
var result = client.DownloadString(endpointUri);
var t = JToken.Parse(result);
return t["d"];
}
}
Dependency: Json.NET library
Usage
The example demonstrates how to retrieve Contacts List and print its title:
static void Main(string[] args)
{
var webUri = new Uri("https://contoso.sharepoint.com");
const string userName = "[email protected]";
const string password = "password";
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}
var credentials = new SharePointOnlineCredentials(userName, securePassword);
var list = GetList(webUri,credentials,"Contacts");
//print List title
Console.WriteLine(list["Title"]);
}
ClientContext.Credentials
property to aSharePointOnlineCredentials
object.