使用客户端对象模型在线访问SharePoint – 禁止错误

我尝试使用客户端对象模型创建一个新的列表项。 我已经创建了一个asp.net应用程序来完成任务。 如果我传递安装在我的计算机中的SharePoint服务器的URL,它就可以工作。 但是,如果我提供我的SharePoint在线URL,它将无法正常工作,如下面的代码所示。 我得到“远程服务器返回错误:(403)禁止。”错误。 任何的想法?

ClientContext context = new ClientContext("https://xxx.sharepoint.com/SitePages/"); List announcementsList = context.Web.Lists.GetByTitle("Announcements"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem newItem = announcementsList.AddItem(itemCreateInfo); newItem["Title"] = result.City; newItem["Body"] = result.State; newItem.Update(); context.ExecuteQuery(); 

如果您尝试从SharePoint Online获取Context对象,则必须输入正确的Credentials ,对于SharePoint Online,您应该使用SharePointOnlineCredentials类

可能的身份validation方法可能如下所示:

 private void AutheticateO365(string url, string password, string userName) { Context = new ClientContext(url); var passWord = new SecureString(); foreach (char c in password.ToCharArray()) passWord.AppendChar(c); Context.Credentials = new SharePointOnlineCredentials(userName, passWord); var web = Context.Web; Context.Load(web); Context.ExecuteQuery(); } 

我想你只需要提供你的登录凭据,它应该工作:

 clientContext.Credentials = new NetworkCredential("Username", "Password", "Domain"); 

你需要包括System.Net:

 using System.Net;