Sharepoint REST API client console application C#

2.1k views Asked by At

I'm looking for the examples to consume the Sharepoint REST API from a C# Console application (read a Sharepoint list to be more exact). There are some tutorials from MS website but they are incomplete in my opinion. For example, this one doesn't show how to acquire the access token and I cannot find any demo code for that: https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-sharepoint-rest-endpoints

This tutorial is exactly what I need, but the code is not working: https://blog.vgrem.com/2015/04/04/consume-sharepoint-online-rest-service-using-net/

private static CookieContainer GetAuthCookies(Uri webUri, string userName, string password)
        {
            var securePassword = new SecureString();
            foreach (var c in password) { securePassword.AppendChar(c); }
            var credentials = new SharePointOnlineCredentials(userName, securePassword);
            var authCookie = credentials.GetAuthenticationCookie(webUri);
            var cookieContainer = new CookieContainer();
            cookieContainer.SetCookies(webUri, authCookie);
            return cookieContainer;
        }

What doesn't work is this line var authCookie = credentials.GetAuthenticationCookie(webUri);. It returns null all the time even though all the webUri, userName, password are correct.

Can someone point me to the right direction or give me an example of client code? The server is running Sharepoint 2013.

1

There are 1 answers

2
Amos On BEST ANSWER

My test code for your reference:

static void Main(string[] args)
        {
            HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create("http://sp/_api/web");
            endpointRequest.Method = "GET";
            endpointRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            endpointRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            //HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
            try
            {
                WebResponse webResponse = endpointRequest.GetResponse();
                Stream webStream = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();//results
                responseReader.Close();
                Console.WriteLine(response);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message); Console.ReadLine();
            }
        }

Or you could use this Credentials:

var username = "administrator";
             var password = "P@ssw0rd";
             var domain = "contoso";
             endpointRequest.Credentials=new System.Net.NetworkCredential(username, password, domain);

SharePoint 2013 does not need to generate the access token.