1
votes

Can I use SharePoint client object model in web part?

This code works in my console application, but in a web part it returns "The remote server returned an error: (401) Unauthorized."

The code is:

var siteUrl = "http://www.server.com/";
var clientContext = new ClientContext(siteUrl);

var root = clientContext.Site.RootWeb;
WebCollection collWeb = root.GetSubwebsForCurrentUser(null);
clientContext.Load(root);
clientContext.Load(collWeb);
clientContext.ExecuteQuery();

The problem might be that the client context does not use the current user credentials. What should I do?

2

2 Answers

2
votes

You add credentials to the clientContext:

System.Net.NetworkCredential cr = new System.Net.NetworkCredential("username", "password"); 

ClientContext clientContext = new ClientContext(siteURL);

clientContext.Credentials = cr;
0
votes

you should try

System.Net.CredentialCache.DefaultCredentials 

to get credential of current user

but, if you are calling a remote sharepoint server, i'm afraid it will NOT works because the double hop problem

the way to call remote sharepoint as CURRENT USER is using ECMA Client Object Model...

of course, the user must allready logedin