2017-06-07 74 views
0

我試圖使用ClientContext(Microsoft.SharePoint.Client lib)連接到Sharepoint。Sharepoint ClientContext始終返回代碼401,當我嘗試連接

不幸的是,當我執行應該在Sharepoint網站上連接的代碼時,我得到了401錯誤。

當我嘗試使用網絡瀏覽器連接時,它工作正常。

這裏說到我的代碼:

 using (ClientContext clientcontext = new ClientContext("http://mysite/")) 
     { 
      var credentials = new NetworkCredential(user, password, domain); 

      clientcontext.Credentials = credentials; 

      Web web = clientcontext.Web; 
      clientcontext.Load(web); 

      clientcontext.ExecuteQuery(); 
     } 

謝謝!

回答

0

使用「Microsoft.SharePoint.Client.dll」和「Microsoft.SharePoint.Client.Runtime.dll」。

using (ClientContext clientcontext = new ClientContext("http://mysite/")) 
    { 
     var credentials = new NetworkCredential(domain\UserName, password); 
     clientcontext.Credentials = credentials; 
     Web web = clientcontext.Web; 
     clientcontext.Load(web); 
     clientcontext.ExecuteQuery(); 
    } 
+0

我使用它,我也試圖把「域\用戶名」。這兩個點都不起作用。 –

0

嗨,對不起。

請參閱下面的工作代碼。 如果您是在線使用SharePoint,使用下面的代碼

public static ClientContext GetClientContext(string url) 
    { 

     SecureString securePassword = new SecureString(); 
     ClientContext context = null; 
     try 
     { 
      using (context = new ClientContext(url)) 
      { 
       foreach (char c in "Password") securePassword.AppendChar(c); 
       context.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword); 
       context.Load(context.Web, w => w.ServerRelativeUrl, w => w.Url); 
       context.ExecuteQuery(); 


      } 
     } 
     catch (Exception ex) 
     { 

     } 

     return context; 
    } 

如果您正在使用本地服務器上的SharePoint,你可以得到的背景下兩種方式。使用應用程序池帳戶或傳遞您的用戶信譽。下面的代碼使用默認的應用程序池憑據。

string parentSiteUrl = Helper.GetParentWebUrl(siteUrl); 
        clientContext = new ClientContext(parentSiteUrl); 
        clientContext.Credentials = CredentialCache.DefaultCredentials; 
        clientContext.Load(clientContext.Web, w => w.Url, w => w.Lists, w => w.ServerRelativeUrl, w => w.Title, w => w.SiteGroups);       
        clientContext.ExecuteQuery(); 

或者您可以通過您的憑據如下。

var clientContext = new ClientContext(siteUrl); 
     clientContext.Credentials = new NetworkCredential("domain\\user", "password"); 
     clientContext.Load(clientContext.Web, w => w.Lists); 
     clientContext.ExecuteQuery(); 

讓我知道你是否有任何疑問。

+0

Thx @Naveen Prasath。但是,我仍然有同樣的問題。我認爲問題是在服務器上安裝Sharepoint。 我會和照顧這臺服務器的團隊覈實一下,如果有的話,我會讓你知道這個解決方案。 –

相關問題