我正在使用 C# 和 CSOM,并且希望通过以下步骤实现 SharePoint Online 网站的目标:
通过给定列表名称获取
list_id
(使用 CSOM 这一步非常简单)使用
list_id
访问页面:https://{domain}.sharepoint.com/_layouts/15/listedit.aspx?List={list_id}
(根据列表ID进入列表设置页面)抓取整个页面的 HTML 内容,然后执行一些进一步的 GET/POST 操作
我的问题是:我陷入了步骤 2 和 3,无法以编程方式登录 SharePoint Online 网站并保留 session 上下文以进行后续的 GET/POST 操作。
实际上,我已经使用
var httpClient = new HttpClient(new HttpClientHandler{Credentials = new NetworkCredential(username, password)}) 在多个 SharePoint OnPerm 网站上成功完成了此操作
然后使用此
HttpClient
登录 OnPerm 站点,并保存登录上下文以进行进一步的 GET/POST 请求
我对 SharePoint Online 的意图与上面相同,使用给定的字符串网站
、字符串用户名
和SecureString 密码
来登录 SharePoint在线站点并以编程方式执行 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 = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87ffffffc7f3e2e9e6e9f3a9e8e9eaeee4f5e8f4e8e1f3a9e4e8ea" rel="noreferrer noopener nofollow">[email protected]</a>";
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();
}
}
}
关于c# - 如何以编程方式登录 SharePoint Online 并获取 Web HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60151040/