c# - 运行此代码时出错 - 通过 C# 中的 Azure 函数将列表项添加到 Sharepoint 在线列表
问题描述
我是新手,作为我的第一个,我正在尝试开发一个 Azure 函数,通过 C# 中的 rest API 将新项目添加到“ID”列到 Sharepoint 在线列表。我已在 Azure 的 Web 门户中编写了此代码,并将其改编为 Visual Studio 以进行故障排除。请任何人提供一些帮助,因为我似乎无法使其正常工作,谢谢。
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using Newtonsoft.Json.Serialization;
using System.Security;
using System.Diagnostics;
using Microsoft.SharePoint.Client;
namespace ConsoleApp1
{
class Program
{
public static async Task<string> GetAuthTokenForSharePoint()
{
Console.WriteLine(" GetAuthTokenForSharePoint was executed!");
HttpClient client = new HttpClient();
string clientId = System.Configuration.ConfigurationManager.AppSettings["123aa123-1234-1234-b1c2-12ab0052c945"];
string clientSecret = System.Configuration.ConfigurationManager.AppSettings["HdvsavdshavshjdvHhhhsdgahsgjhwqj08="];
string tenantId = System.Configuration.ConfigurationManager.AppSettings["123a1a23-1ab4-4a44-b3c7-abc00d12345e"];
string spTenantUrl = System.Configuration.ConfigurationManager.AppSettings["https://mytenant.sharepoint.com"];
string spPrinciple = "00000003-0000-0ff1-ce00-000000000000";
string spAuthUrl = "https://accounts.accesscontrol.windows.net/" + tenantId + "/tokens/OAuth/2";
KeyValuePair<string, string>[] body = new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", $"{clientId}@{tenantId}"),
new KeyValuePair<string, string>("resource", $"{spPrinciple}/{spTenantUrl}@{tenantId}".Replace("https://", "")),
new KeyValuePair<string, string>("client_secret", clientSecret)
};
var content = new FormUrlEncodedContent(body);
var contentLength = content.ToString().Length;
string token = "";
Console.WriteLine(content.ToString());
using (HttpResponseMessage response = await client.PostAsync(spAuthUrl, content))
{
if (response.Content != null)
{
Console.WriteLine("Something went wrong in getting token much earlier");
string responseString = await response.Content.ReadAsStringAsync();
JObject data = JObject.Parse(responseString);
token = data.Value<string>("access_token");
}
else
{
Console.WriteLine("Something went wrong in getting token");
}
}
return token;
}
public static async Task<string> GetDigestForSharePoint(string siteUrl, string token)
{
Console.WriteLine("GetDigestForSharePoint was executed!");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("accept", "application/json;odata=verbose");
StringContent content = new StringContent("");
string spTenantUrl = System.Configuration.ConfigurationManager.AppSettings["https://mytenant.sharepoint.com"];
string digest = "";
// using (HttpResponseMessage response = await client.PostAsync())$"{spTenantUrl}{siteUrl}/_api/contextinfo"
using (HttpResponseMessage response = await client.PostAsync("https://mytenant.sharepoint.com/sites/mySite", content))
{
if (response.IsSuccessStatusCode)
{
string contentJson = response.Content.ReadAsStringAsync().Result;
JObject val = JObject.Parse(contentJson);
JToken d = val["d"];
JToken wi = d["GetContextWebInformation"];
digest = wi.Value<string>("FormDigestValue");
}
}
return digest;
}
public static async Task CreateSharePointListItem(string siteUrl, string listName, string itemTitle)
{
Console.WriteLine("CreateSharePointListItem was executed!");
try
{
var token = await GetAuthTokenForSharePoint();
Console.WriteLine(token);
var digest = await GetDigestForSharePoint(siteUrl, token);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
HttpContent content = new StringContent($"{{ '__metadata': {{ 'type': 'SP.ListItem' }}, 'Title': '{itemTitle}'}}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));
string spTenantUrl = System.Configuration.ConfigurationManager.AppSettings["https://mytenant.sharepoint.com"];
using (HttpResponseMessage response = await client.PostAsync($"{spTenantUrl}{siteUrl}/_api/web/Lists/GetByTitle('{listName}')/items", content))
{
if (!response.IsSuccessStatusCode)
//log.Error($"The REST call to SharePoint failed: {response.StatusCode.ToString()}.");
Console.WriteLine(response.StatusCode.ToString());
}
}
catch (Exception ex)
{
//log.Error($"Could not write SharePoint list item: {ex}");
Console.WriteLine(ex);
}
}
public static async void Run()
{
Console.WriteLine("Run was executed!");
await CreateSharePointListItem("/sites/mySite", "myList", "ID");
}
static void Main(string[] args)
{
Program.Run();
}
}
}
解决方案
推荐阅读
- javascript - WEBPACK - 如何从文件夹中获取单个 css 文件
- reactjs - 如何使用反应“获取和更新用户详细信息并将其保存在 Firebase 中”
- reactjs - React Big Calendar 只显示特定的时间范围
- mongodb - 仅调用 Typegoose 进行保存操作时,钩子在 updateOne 上不起作用
- bots - 我应该在什么环境下为电报机器人编写代码,以便即使在控制台未运行时它也能正常工作?
- javascript - 如何使用 const 变量来迭代“for in”循环?
- javascript - bootstrap 中的 toasts 动画
- javascript - 选择特定日期时显示错误(日期输入)
- python - 不同长度的二维绘图 xy 列表
- inheritance - 如何让一个小部件从另一个小部件继承?- 颤振