微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.NET Core:使用 SharePoint API 将文件添加到 SharePoint

如何解决.NET Core:使用 SharePoint API 将文件添加到 SharePoint

请注意这是 .NET Core。我们已经设置了 Azure AD,我们能够生成访问令牌。问题是当我们尝试将文件发送到 SharePoint 时,我们不断收到 (401) 未经授权的错误。有限的代码示例似乎存在,但从我所见,您应该能够将令牌放入标头并调用 API。正在生成令牌。它就在那里。

CSOM 已添加解决方案中,但使用“SharePointOnlineCredentials”登录的简单方法在 .NET 核心中不起作用。它需要 oAuth 令牌。

SharePoint 的 Azure API 权限为“AllSites.Manage、AllSites.Read、AllSites.Write、MyFiles.Read、MyFiles.Write、Sites.SearchAll”

知道我在这里做错了什么吗?这些网址在浏览器中有效。

public static void SaveFile()
    {
        //This sets the token and the token is there
        string getToken = SharePointSetToken.SetToken();

        if (!String.IsNullOrEmpty(getToken))
        {

            //The site URL
            string siteUrl = "https://MySite.sharepoint.com";

            //The folder in the site to add the file too
            string folderUrl = "/sites/MyDocuments/";

            //The file
            string p = @"C:\MyFolder\MyFile.pdf";

            //The API call
            string spUrl = siteUrl + "/_api/web/getfolderbyserverrelativeurl('" + folderUrl + "')/Files/add(url='" + System.IO.Path.GetFileName(p) + "',overwrite=true)";
            
            //The request parameters
            HttpWebRequest webRequest;
            webRequest = (HttpWebRequest)HttpWebRequest.Create(spUrl);
            webRequest.Method = "POST";
            webRequest.Headers.Add("binaryStringRequestBody","true");
            webRequest.Headers.Add("Authorization","Bearer " + getToken);

            //File as byte[]
            byte[] bytefile = System.IO.File.ReadAllBytes(p);

            //Save it to SP
            webRequest.GetRequestStream().Write(bytefile,bytefile.Length);

            //Error Here: 401 The Remote Server returned an error: (401) Unauthorized.
            HttpWebResponse endpointresponse = (HttpWebResponse)webRequest.GetResponse();
        }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。