Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Can someone please shed some light on this? I am working on a task to generate an on demand spreadsheet/document and upload the generated document to SharePoint 2013 (on-prem) from .net core 2.0 application. I am using Epplus.core libraries to generate the spreadsheet. Using CSOM is not an option for me as I didn't find any nuget libraries which support .net core 2.0 framework so, I am trying to use SP REST API to upload the generated document.

Here's my sample code to test upload a document to sharepoint.

<pre>using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\test.xlsx"; //File to be uploaded
            string siteurl = "https://SpSite"; //site on which file needs to be uploaded (don't put  / at end)
            string documentlibrary = "DocumentLibrary"; //Document library where file needs to be uploaded
            bool filestatus = UploadUsingRest(siteurl, documentlibrary, filePath);
            if (filestatus)
            {
                Console.WriteLine("File uploaded successfully");
            }
            else
            {
                Console.WriteLine("Error uploading file");
            }
        }

        //Method to upload File
        public static bool UploadUsingRest(string siteurl, string libraryName, string filePath)
        {
            bool status = false;
            byte[] binary = System.IO.File.ReadAllBytes(filePath);
            string fname = System.IO.Path.GetFileName(filePath);
            string result = string.Empty;
            //Url to upload file
            string resourceUrl = siteurl + "/_api/web/GetFolderByServerRelativeUrl('" + libraryName + "')/Files/add(url='" + fname + "',overwrite=true)";
            HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
            wreq.UseDefaultCredentials = false;
            //credential who has edit access on document library
            NetworkCredential credentials = new System.Net.NetworkCredential("username", "password", "domain");
            wreq.Credentials = credentials;
            //wreq.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            //Get formdigest value from site
            string formDigest = GetFormDigestValue(siteurl, credentials);            
            wreq.Headers.Add("X-RequestDigest", formDigest);
            wreq.Method = "POST";
            wreq.Timeout = 1000000; //timeout should be large in order to upload file which are of large size
            wreq.Accept = "application/json; odata=verbose";
            wreq.ContentLength = binary.Length;
            try
            {
                using (System.IO.Stream requestStream = wreq.GetRequestStream())
                {
                    requestStream.Write(binary, 0, binary.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {
                WebResponse wresp = wreq.GetResponse();
                using (System.IO.StreamReader sr = new System.IO.StreamReader(wresp.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                    status = true;
                    return status;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return status;
                throw;
            }
        }

        //Method which return form digest value
        private static string GetFormDigestValue(string siteurl, NetworkCredential credentials)
        {
            string newFormDigest = "";
            HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(siteurl + "/_api/contextinfo");
            endpointRequest.Method = "POST";
            endpointRequest.ContentLength = 0;
            endpointRequest.Credentials = credentials;
            endpointRequest.Accept = "application/json;odata=verbose";
            //endpointRequest.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";

            try
            {
                HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {
                WebResponse webResp = endpointRequest.GetResponse();
                Stream webStream = webResp.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();
                var j = JObject.Parse(response);
                var jObj = (JObject)JsonConvert.DeserializeObject(response);
                foreach (var item in jObj["d"].Children())
                {
                    newFormDigest = item.First()["FormDigestValue"].ToString();
                }
                responseReader.Close();

            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }

            return newFormDigest;
        }
    }
}


What I have tried:

I have tried using defaultcredentials, tried passing in useragent to the request. Tried adding in an header for FBA as well. It seems like this is an issue with authentication/authorization. Let me know if anything has to be changed on or if adfs has to be disabled etc.
Posted
Updated 28-Dec-17 17:27pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900