1

I was trying to test creating folder under root folder in sharepoint online using access token and REST API using HTTPWebRequest classes from console application.

I don't want to use any sharepoint assemblies as since I can't actually use this in my final code. But always getting 403 Forbidden exception when getting the response.

Can any one kindly suggest if any useful reference documentation for this issue?

Code I am using:

void CreateFolder(string token, string library, string folder)
                {
                    string sharePointSite = "https://xxx.sharepoint.com/sites/xxx";                
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sharePointSite + "/_api/lists/getByTitle('" + library + "')");
                    //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sharepointURL + "/_api/lists/getByTitle('" +library + "')/rootfolder/folders/add(url ='" +folder + "')");
                    request.Method = "POST";
                    request.Accept = "application/json; odata=verbose";
                    //request.Headers.Add(HttpRequestHeader.Authorization, "Bearer" + token);
                    myWebRequest.Headers.Add("Authorization", "Bearer");
                    ASCIIEncoding encoding = new ASCIIEncoding();
                    //byte byte1 = encoding.GetBytes(request);
                    request.ContentLength = 0;
                    Console.WriteLine(request);

                    try
                    {
                        if (request.GetResponse().ToString() != null)
                        {
                            using (WebResponse response = request.GetResponse())
                            {
                                Console.WriteLine(response);
                                Console.ReadKey();
                            }
                            // Do something if the resource has changed.

                        }
                    }
                    catch (WebException wex)
                    {

                        HttpWebResponse httpResponse = wex.Response as HttpWebResponse;
                        if (httpResponse.StatusCode != (HttpStatusCode.NotModified))
                        {                            // resource was not modified.
                            Console.WriteLine("Error occured from line 195");
                        }
                        // Something else happened. Rethrow or log.
                        //throw;
                    }
                    catch (Exception ex)
                    {    // Something else happened. Rethrow or log
                        Console.WriteLine("Error occured from line 203");                        
                    }

2 Answers 2

0

You need to Authenticate before making POST requests. So, try using below code:

public static void CreateFolder()
 {
             string result = string.Empty;
             Uri uri = new Uri("http://basesmc15/_api/web/folders");
             HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(uri);
             wreq.Credentials = CredentialCache.DefaultNetworkCredentials;

             wreq.Method = "POST";
             wreq.Accept = "application/json; odata=verbose";
             wreq.ContentType = "application/json; odata=verbose";
             wreq.Headers.Add("X-HTTP-Method", "POST");
             wreq.Headers.Add("X-RequestDigest", GetFormDigest());

             string stringData = "{'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/shared documents/foldername2'}";
             wreq.ContentLength = stringData.Length;
             StreamWriter writer = new StreamWriter(wreq.GetRequestStream());
             writer.Write(stringData);
             writer.Flush();

             WebResponse wresp = wreq.GetResponse();
             using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
             {
                 result = sr.ReadToEnd();
             }
}

Source: Not able to create a Folder in sharepoint 2013 online.

3
  • Thank you Ganesh for your reply, I was authenticating using Access token to site earlier...the code sample which you sent fails with the same 403 error at GetFormDigest method...can you please suggest on using this with access token approach...this is for sharepoint online... Mar 5, 2020 at 5:57
  • Try using the GetDigest method as mentioned here. Mar 5, 2020 at 6:19
  • Thank you Ganesh...this approach uses await functions...my final code needs to executed in 2mins, so couldnt go with this approach...can you please suggest any alternative... Mar 6, 2020 at 5:53
0

I was able to achieve using below approach, posting so that some one can make use of this:


public void CreateFolder(string sharePointSite, string token, string library, string folder,Guid entityID)
        {
                   if (library == "contact")
            {
                Entity contact = _service.Retrieve("contact", entityID, new ColumnSet("suffix"));            
                string knownas = contact.GetAttributeValue<string>("suffix");
                knownas = knownas.Replace("/", "").Replace("&","");//replaced explicity as WebUtility.UrlEncode doesn't handle                
                folder = folder + "_" + WebUtility.UrlEncode(knownas);                
            }
            string result = string.Empty;
            StringBuilder sb = new StringBuilder();
            sb.Append(sharePointSite);
            sb.Append("_api/web/GetFolderByServerRelativePath(decodedUrl='");
            sb.Append(library);
            sb.Append("')/Folders");
            Uri uri = new Uri(sb.ToString().Replace("{", "").Replace("}", ""));            
            HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(uri);
            wreq.Headers.Add("Authorization", "Bearer " + token);
            wreq.Method = "POST";
            wreq.ContentType = "application/json";
            string postData = "{'ServerRelativeUrl':'folder'}";
            postData = postData.Replace("folder", folder);            
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            wreq.ContentLength = postData.Length;
            Stream dataStream = wreq.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse wresp = null;
            try
            {
                wresp = wreq.GetResponse();
                using (wresp = wreq.GetResponse())
                {
                    dataStream = wresp.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream);
                    string responseFromServer = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (WebException wex)
            {
                HttpWebResponse httpResponse = wex.Response as HttpWebResponse;
                createlog(_service, "Error occured" + wex.ToString());
                throw new InvalidPluginExecutionException("Exception occured while creating record" + wex.ToString());
            }
}

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.