如何使用 C# 中的 CSOM 连接到 Office 365 上的 SharePoint?

问题描述:

我无法连接到 Office 365 上的新开发 SharePoint Online 网站.我可以从浏览器查看该网站和列表,并且我已添加一个 API 用户作为网站管理员和 O365 管理员.调用 ClientContext.ExecuteQuery() 时,我不断收到 401 错误.任何建议表示赞赏.

I'm having trouble connecting to a new dev SharePoint Online site on Office 365. I can view the site and a list from a browser, and I've added an API user as a site admin and an O365 admin. I keep getting a 401 error when calling ClientContext.ExecuteQuery(). Any advice is appreciated.

我不知道是我访问了错误的 URL 还是用户没有权限,或者可能完全不同.我已经测试了用户名和密码,因为如果我使用错误的密码,它会给我一个关于无效用户的不同错误.所以,我很确定我有正确的凭据.用户已被设置为 O365 管理员,并已通过该控制台被授予对 SharePoint 网站的编辑"权限.我什至尝试过使用我自己的凭据,而且我是创建该站点的人.

I don't know whether I'm hitting the wrong URL or the user doesn't have rights, or maybe it's something totally different. I've tested the username and password, as it gives me a different error about an invalid user if I use the wrong password. So, I'm pretty sure that I have the right credentials. The user has been set as an O365 admin and has been granted "Edit" rights to the SharePoint site through that console. I've even tried using my own credentials, and I'm the one that created the site.

我的目标是最终从特定列表中获取列表项.不过,既然我做不到这么多,我也没有走得太远.

My goal is to eventually get list items from a particular list. However, since I can't do this much, I haven't gotten too far.

以下是控制台应用的一些示例代码:

Here's some sample code from a console app:

ClientContext cc;
SecureString pw;

cc = new ClientContext("http://XXXX.sharepoint.com");
pw = new SecureString();
"XXXX".ToCharArray().ToList().ForEach(c => pw.AppendChar(c));
cc.Credentials = new SharePointOnlineCredentials("api@XXXX.onmicrosoft.com", pw);
cc.Load(cc.Web);
cc.ExecuteQuery();

试试这个:

ClientContext cc = new ClientContext("https://XXXX.sharepoint.com");
SecureString pass = new SecureString();

foreach (char c in "XXXX".ToCharArray();
    pass.AppendChar(c);

cc.Credentials = new SharePointOnlineCredentials("api@XXXX.onmicrosoft.com", pass);
cc.Load(cc.Web);
cc.ExecuteQuery();