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



我正在寻找从C#控制台应用程序中使用Sharepoint REST API的示例(更确切地说,请阅读Sharepoint列表(。MS网站上有一些教程,但在我看来它们是不完整的。例如,这个没有显示如何获取访问令牌,我找不到任何演示代码:https://learn.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、userName和密码都是正确的,它也始终返回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不需要生成访问令牌。

最新更新