如何通过GraphAPI在SharePoint列表中插入数据?

时间:2018-09-03 13:45:46

标签: sharepoint microsoft-graph

我有一个SharePoint列表,其中包含参考号。其URL如下所示: https://xyz.sharepoint.com/sites/site_name/Lists/List_name/AllItems.aspx

此列表内容参考号。我正在尝试将此数据插入列表中。

{
"Optimum_x0020_Case_x0020_Reference": "000777"
} 

这是我要发布数据的网址。 https://graph.microsoft.com/v1.0/sites/xyz.sharepoint.com:/sites/site_name:/lists/List_names/items

但是我收到此错误:

error": {
"code": "accessDenied",
"message": "The caller does not have permission to perform the action.",

该如何解决?使用访问权限,我可以创建文件夹,子文件夹并为其他文档更新元数据。

1 个答案:

答案 0 :(得分:0)

您在做什么的背景是什么?它是您正在使用的应用程序吗?您是要在现有的列表项还是新项上插入数据?

这是我必须用于UWP App的代码。我不确定这是否对您有帮助,但是我希望它会给您一些指导。创建字典并弄清楚XML结构是我必须拼凑起来才能使代码正常工作的关键。

我在App.xaml.cs中声明了作用域

    public static string[] scopes = new string[] { "user.ReadWrite", "Sites.ReadWrite.All", "Files.ReadWrite.All" };

我在主页上使用了一个提交按钮

    private async void SubmitButton_Click(object sender, RoutedEventArgs e)
    {
       var (authResult, message) = await Authentication.AquireTokenAsync();

        if (authResult != null)
        {
            await SubmitDataWithTokenAsync(submiturl, authResult.AccessToken);
        }
    }

这将调用我在类文件中拥有的AquireToken:

    public static async Task<(AuthenticationResult authResult, string message)> AquireTokenAsync()
    {
        string message = String.Empty;
        string[] scopes = App.scopes;

        AuthenticationResult authResult = null;
        message = string.Empty;
        //TokenInfoText.Text = string.Empty;

        IEnumerable<IAccount> accounts = await App.PublicClientApp.GetAccountsAsync();
        IAccount firstAccount = accounts.FirstOrDefault();

        try
        {
            authResult = await App.PublicClientApp.AcquireTokenSilentAsync(scopes, firstAccount);
        }
        catch (MsalUiRequiredException ex)
        {
            // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
            System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

            try
            {
                authResult = await App.PublicClientApp.AcquireTokenAsync(scopes);
            }
            catch (MsalException msalex)
            {
                message = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
            }
        }
        catch (Exception ex)
        {
            message = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
        }
        return (authResult,message);
    }

我为SharePointList创建了另一个类

公共类SharePointListItems {     公共类查找     {         公共字符串SerialNumber {get;组; }         公开字串编号{组; }         公共重写字符串ToString()         {             返回序列号;         }     }

public class Value
{
    public Lookup fields { get; set; }
}

    public class Fields
    {
        [JsonProperty("@odata.etag")]
        public string ODataETag { get; set; }

        public string ParameterA { get; set; }
        public string ParameterB { get; set; }
        public string ParameterC { get; set; }
    }

    public class RootObject
    {
        [JsonProperty("@odata.context")]
        public string ODataContext { get; set; }

        [JsonProperty("@odata.etag")]
        public string ODataETag { get; set; }

        [JsonProperty("fields@odata.context")]
        public string FieldsODataContext { get; set; }

        public Fields Fields { get; set; }
    }    
}

我使用此类创建了一个字典,用于将数据提交到SharePoint。

    public async Task<string> SubmitDataWithTokenAsync(string url, string token)
    {
        var httpClient = new HttpClient();
        HttpResponseMessage response;
        try
        {
            var root = new
            {
                fields = new Dictionary<string, string>
                {
                   // The second string are public static strings that I
                   // I declared in my App.xaml.cs because of the way my app
                   // is set up.
                   { "ParameterA", App.ParameterA },
                   { "ParameterB", App.ParameterB },
                   { "ParameterC", App.ParameterC },
                }
            };

            var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
            var content = JsonConvert.SerializeObject(root, s);
            var request = new HttpRequestMessage(HttpMethod.Post, url);
            //Add the token in Authorization header
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            request.Content = new StringContent(content, Encoding.UTF8, "application/json");
            response = await httpClient.SendAsync(request);
            var responseString = await response.Content.ReadAsStringAsync();                
            return responseString;
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

然后定义了我的SubmitURL:

    public static string rooturl = "https://graph.microsoft.com/v1.0/sites/xxxxxx.sharepoint.com,495435b4-60c3-49b7-8f6e-1d262a120ae5,0fad9f67-35a8-4c0b-892e-113084058c0a/";
    string submiturl = rooturl + "lists/18a725ac-83ef-48fb-a5cb-950ca2378fd0/items";

您也可以查看我在类似主题here上发布的问题。