Ошибка при запуске этого кода - добавление элемента списка в онлайн-списки Sharepoint с помощью функций Azure в C # - PullRequest
0 голосов
/ 01 июля 2019

Я новичок в этом и, как мой первый, я пытаюсь разработать функцию Azure, чтобы добавить новый элемент в столбец 'ID' в онлайн-список Sharepoint с помощью API rest в C #. Я написал этот код на веб-портале Azure и адаптировал его в 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();

    }
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...