1
votes

I'm trying to connect to a Sharepoint using ClientContext (Microsoft.SharePoint.Client lib).

Unfortunately, when I execute the code that supposed to connect on Sharepoint Site, I'm getting 401 error.

When I try to connect using a web browser it works fine.

Here comes my code:

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

Thanks!

2

2 Answers

1
votes

Hi sorry for the delay.

Please see my working code below. If you are using SharePoint online, use below code

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

If you are using SharePoint on premises server, you can get the context in two ways. Using app pool account or by passing your user creds. Below code using the default app pool credentials.

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

Or you can pass your credentials as below.

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

Let me know if you have any queries.

0
votes

Use "Microsoft.SharePoint.Client.dll" and "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();
    }