0

I am trying to get the list items from SharePoint. While executing the following code, I am getting "the remote server returned an error (403) forbidden".

 try
        {
            using (var context = new ClientContext(siteurl + "/_api/lists/GetByTitle('" + documentlibrary + "')/items?$orderby=Id%20desc"))
            {
                context.Credentials = new SharePointOnlineCredentials("[email protected]", GetPasswordOfYourSite("password"));
                Web web = context.Web;
                context.Load(web.Lists,
                    lists => lists.Include(list => list.Title,
                        list => list.Id));
                context.ExecuteQuery();
                Console.ForegroundColor = ConsoleColor.White;
                foreach (List list in web.Lists)
                {
                    Console.WriteLine("List title is: " + list.Title);
                }
                Console.WriteLine("");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error is: " + ex.Message);
        }

while trying to connect, getting this "the remote server returned an error (403) forbidden" exception.

Could you please what are the reasons for this issue? and how to resolve this?

thanks

2 Answers 2

0

Change

using(var context = new ClientContext(siteurl + "/_api/lists/GetByTitle('" + documentlibrary + "')/items?$orderby=Id%20desc"))

to

using (var context = new ClientContext(siteurl))

The syntax you are passing in ClientContext is used in REST and not in .Net Managed code. Here only siteurl will do the job and should fix your 403 error.

1
  • Thank you so much.
    – AVG
    Nov 15, 2019 at 14:15
0

You need to change this line

using (var context = new ClientContext(siteurl + "/_api/lists/GetByTitle('" + documentlibrary + "')/items?$orderby=Id%20desc"))

to this

using (var context = new ClientContext(siteurl))

The URL you pass to the ClientContext constructor should be the URL to a site collection. You added a SharePoint REST API resource URL to that URL. This is unnecessary because the remainder of your code uses the SharePoint Client Object Model to implement the desired functionality.

You can get more information on the REST API and the Client Object Model by reviewing the materials for my conference talk: Introduction to the SharePoint Client Object Model and REST API

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.