【问题标题】:Update sharepoint list item in C# via graph api with error 400 bad request通过图形 api 更新 C# 中的共享点列表项,错误 400 错误请求
【发布时间】:2024-05-22 05:55:02
【问题描述】:

我已经在 SharePoint 列表中创建了一个包含“ScheduledTimeSlot”的列,但不知何故我似乎无法更新此列。

验证 itemId,访问令牌是正确的,因为我可以使用另一种方法创建项目,只是在更新项目时遇到问题。

当我使用 string addItemJsonString = "{\"ScheduledTimeSlot\":\"13XX17101310238\"}"; 有效。但是当我尝试以下方法时,它会给我错误的请求错误 400。我很确定这是格式问题。

        var root = new
        {
            fields = new Dictionary<string, string>
        {
            { "ScheduledTimeSlot", scheduledTimeSlot },  //column to update
        }
        };
        string addItemJsonString = JsonConvert.SerializeObject(root);

下面的完整方法

    public async Task UpdateSharePointListItem(string webApiUrl, string itemId, string scheduledTimeSlot, string accessToken)
    {
        Console.WriteLine(itemId);
        Console.WriteLine(scheduledTimeSlot);
        var root = new
        {
            fields = new Dictionary<string, string>
        {
            { "ScheduledTimeSlot", scheduledTimeSlot },  //column to update
        }
        };

        string addItemJsonString = JsonConvert.SerializeObject(root);
        Console.WriteLine(addItemJsonString);
        string requestUrl = config.ApiUrl + "v1.0/sites/" + config.SiteId + "/lists/" + config.ListId + "/items/" + itemId + "/fields";
        HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("PATCH"), requestUrl);
        message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        message.Content = new StringContent(addItemJsonString, Encoding.UTF8, "application/json");
        HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
        HttpResponseMessage response = await HttpClient.SendAsync(message);
        Console.WriteLine(response);
    }

我也尝试过这里的解决方案:How to PATCH data using System.Net.Http

【问题讨论】:

    标签: c# microsoft-graph-api


    【解决方案1】:

    设法找出如下所示的格式以进行更新。必须删除字段括号以进行更新。

                var root = new
                {
                    ScheduledTimeSlot = scheduledTimeSlot
                };
                string addItemJsonString = JsonConvert.SerializeObject(root);
    
    

    当您尝试更新共享点列表时,请记住使用 PATCH 而不是 POST。

    【讨论】:

      最近更新 更多