如何以编程方式登录 SharePoint Online 并获取网络 HTML?

How to programmatically login on SharePoint Online and get web HTML?

我正在使用 C# 和 CSOM,并希望通过以下步骤实现 SharePoint Online 网站的目标:

  1. 通过给定的列表名称获取 list_id(使用 CSOM 这一步非常简单)

  2. 使用list_id访问页面:https://{domain}.sharepoint.com/_layouts/15/listedit.aspx?List={list_id}(根据列表ID设置列表页面)

  3. 抓取整个页面 HTML 内容,然后做一些进一步的 GET/POST 操作

我的问题是:我卡在第 2 步和第 3 步,无法以编程方式登录到 SharePoint Online 网站并保持会话上下文以进行进一步的连续 GET/POST 操作。


我对 SharePoint Online 的意图与上述相同,使用给定的 string sitestring usernameSecureString password,登录 SharePoint Online 网站并以编程方式执行 GET/POST .


目前我只是使用 SharePointOnlineCredentials 替换 NetworkCredential 以获得 HttpClient 用于登录,但只会出现 401 和 502 错误。

我们可以使用 WebClient 在 SharePoint 中获取页面 HTML。以下代码供大家参考。

using System;
using System.Security;
using Microsoft.SharePoint.Client;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "https://tenant.sharepoint.com";
            string userName = "xxx@tenant.onmicrosoft.com";
            string password = "xxx";
            string listName = "listname";

            var securePassword = new SecureString();
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }

            var credentials = new SharePointOnlineCredentials(userName, securePassword);
            var ctx = new ClientContext(siteUrl);
            ctx.Credentials = credentials;
            var list = ctx.Web.Lists.GetByTitle(listName);
            ctx.Load(list);
            ctx.ExecuteQuery();

            using (var wc = new System.Net.WebClient())
            {
                wc.Credentials = credentials;
                wc.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MDDC)";
                var pageHtml = wc.DownloadString(siteUrl + "/_layouts/15/listedit.aspx?List={" + list.Id.ToString() + "}");
                Console.WriteLine(pageHtml);
            }          
            Console.ReadKey();
        }
    }
}