0

I'm trying to upload a file to SharePoint 2016 On-Prem via the REST API, I'm currently getting 403 Forbidden Response.

SharePoint is sat behind ADFS, I'm successfully authenticating, and I'm sending the FedAuth cookie as part of the REST call. Note, I can successfully download from SharePoint using the REST API, however, I'm unable to upload.

Web Call:

using (var client = new WebClient())
{
    var endpointUri = new Uri("https://site.mySharePoint.com/sites/mySite/_api/web/getfolderbyserverrelativeurl('/sites/mySite/Shared%20Documents/')/Files/add(overwrite=true,url='test.jpg')");

    string filePath = "C:\\temp\\image.jpg";
    var fileContent = System.IO.File.ReadAllBytes(filePath);
    var fileName = System.IO.Path.GetFileName(filePath);
    client.Headers.Add(HttpRequestHeader.Cookie, cook2);

    client.UploadData(endpointUri, "POST", fileContent);
    Console.ReadKey();
}

Any help? Thanks.

0

If you can use C# and you are not developing for the mobile platform I would just use CSOM. it's way easier to use than REST. It's smart enough to know how to authenticate properly with or without ADFS.

I'm not 100% sure, but I think that in your case, you can probably download the file, but not upload it because you don't add X-RequestDigest header to your request. Downloading the file does not require it, but any post does.

Here is an example that uses HttpClientHandler instead of the WebClient, but the idea is the same:

    public async Task<string> UploadFile(byte[] image, string listTitle, string relativePath, string uploadFileName)
    {
        string endpointUrl = _siteUrl + String.Format(
           "/_api/web/GetFolderByServerRelativeUrl('{0}')/Files/Add(url='{1}', overwrite=true)",
           relativePath,
           uploadFileName);

        HttpClientHandler httpHandler = new HttpClientHandler();
        httpHandler.CookieContainer = cc;

        HttpClient client = new HttpClient(httpHandler);
        client.DefaultRequestHeaders.Add("X-RequestDigest", _DigestValue);

        try
        {
            ByteArrayContent imageBytes = new ByteArrayContent(image);
            var result = await client.PostAsync(endpointUrl, imageBytes);
            return result.Content.ToString();
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

Here is a basic example of playing with REST via C# that I've written a couple of years ago:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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