Search code examples
c#sharepointsharepoint-2013web-partsdatacontext

401 Unauthorized exception throws on Sharepoint Webpart using DataContext


I'm using the below code to create a new instance of Sharepoint datacontext:

spDataContext con = new spDataContext(new Uri("http://mysite/subsite/_vti_bin/ListData.svc"));
con.Credentials = CredentialCache.DefaultCredentials;

Then I try fetching the items by using

var result = con.testingList.ToList();

Then Below error shows:

"401 UNAUTHORIZED"

Here's the screenshot of the error:

enter image description here

But if I change the credentials by providing the sharepoint admin username and password, I am able to fetch the items.

con.Credentials = new NetworkCredential(username, password);

But the problem is: I want to use the current user's credentials instead of administrator account, since not all the items are supposed to be seen by current user.

Some addition information from the IIS:

enter image description here

At first, all authentication methods are enabled, then I tried turning off basic and digest authentication to see if it helps, but the exception still throws.

So how to fix this problem??


Solution

  • At last the reason was:

    I don't have the System.Web assembly in the class library, so the system was unable to get the CredentialCache.DefaultCredentials.

    enter image description here