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

来自 SharePoint Online 的 FormDigest 返回未经授权的错误

如何解决来自 SharePoint Online 的 FormDigest 返回未经授权的错误

我正在尝试从 SharePoint Online 获取 FormDigest。我正在使用登录 SharePoint 站点时有效的凭据。但是,当我通过 C# 连接到 SharePoint 时,它给出了 *

远程服务器返回错误:(401) Unauthorized。

错误。 下面是相同的代码

public static string GetFormDigest()
        {
            string formDigest = null;
            try
            {
                const string RESTURL = "{0}/_api/contextinfo";
                string restUrl = string.Format(RESTURL,sharepointUrl);
                HttpWebRequest wreq = HttpWebRequest.Create(restUrl) as HttpWebRequest;

                var securePassword = new securestring();
                //Convert string to secure string  
                foreach (char c in password)
                    securePassword.AppendChar(c);
                securePassword.MakeReadOnly();

                var creds = new SharePointOnlineCredentials(username,securePassword);

                wreq.Credentials = creds;
                wreq.Method = "POST";
                wreq.Accept = "application/json;odata=verbose";
                wreq.ContentLength = 0;
                wreq.ContentType = "application/json";
                wreq.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED","f");
                wreq.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
                WebResponse wresp = wreq.GetResponse();

                string result;
                using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }

                var jss = new JavaScriptSerializer();
                var val = jss.Deserialize<Dictionary<string,object>>(result);
                var d = val["d"] as Dictionary<string,object>;
                var wi = d["GetContextWebinformation"] as Dictionary<string,object>;
                formDigest = wi["FormDigestValue"].ToString();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return formDigest;

        }

方法#2

using (var clientContext = new ClientContext("<<SharePointURL>>"))
                {
                    var securedPassword = GetSecuredPassword();
                    // SharePoint Online Credentials  
                    clientContext.Credentials = new SharePointOnlineCredentials(username,securedPassword);
                    // Get the SharePoint web  
                    Web web = clientContext.Web;
                    // Load the Web properties  
                    clientContext.Load(web);
                    // Execute the query to the server.  
                    clientContext.ExecuteQuery();
                    // Web properties - display the Title and URL for the web  
                    Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
                    Console.ReadLine();
                }

方法#3

public static async void GetDigest()
        {
            try
            {
                const string RESTURL = "{0}/_api/contextinfo";
                string restUrl = string.Format(RESTURL,sharepointUrl);
                var uri = new Uri(restUrl);
                var credentialsCache = new CredentialCache
                    {{uri,"NTLM",new NetworkCredential(username,password,domain)}};
                var handler = new httpclienthandler {Credentials = credentialsCache};
                var httpClient = new HttpClient(handler) {BaseAddress = uri};
                httpClient.DefaultRequestHeaders.ConnectionClose = false;
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type","text/xml");
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("DataServiceVersion","3.0");
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Host","helenoy.sharepoint.com");
                ServicePointManager.FindServicePoint(uri).ConnectionLeaseTimeout =
                    120 * 1000; // Close connection after two minutes
                var response = httpClient.PostAsync(uri,null).Result;
                string respdata = await response.Content.ReadAsstringAsync();
                Console.WriteLine(respdata);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace + ex.Message);
            }
        }

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