Sharepoint REST API 客户端控制台应用程序 C#

Sharepoint REST API client console application C#

我正在寻找从 C# 控制台应用程序使用 Sharepoint REST API 的示例(更准确地说,阅读 Sharepoint 列表)。 MS 网站上有一些教程,但我认为它们不完整。例如,这个没有显示如何获取访问令牌,我找不到任何演示代码: https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-sharepoint-rest-endpoints

本教程正是我所需要的,但代码无法运行: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;
        }

这一行不起作用var authCookie = credentials.GetAuthenticationCookie(webUri);。即使所有的 webUri、用户名、密码都是正确的,它 returns 始终为 null。

有人可以指出正确的方向或给我一个客户端代码示例吗?服务器是 运行 Sharepoint 2013。

我的测试代码供大家参考:

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();
            }
        }

或者您可以使用此凭据:

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

SharePoint 2013 不需要生成访问令牌。