You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 调用Graph API更新SharePoint列表项返回400 Bad Request错误

错误原因
  1. JSON结构不匹配
    你硬编码的请求体是直接包含字段键值对的结构:
{"ScheduledTimeSlot":"13XX17101310238"}

但你用匿名对象序列化的结果外层多了一层fields节点,实际生成的结构是:

{"fields":{"ScheduledTimeSlot":"xxx"}}

你调用的/items/{itemId}/fields端点的PATCH请求,要求请求体直接传递字段键值对,不需要外层包裹fields,结构不符直接触发400错误。
2. 请求头重复设置
你已经在StringContent构造时指定了application/json类型,又额外给HttpClient.DefaultRequestHeaders添加了Content-Type配置,重复的请求头设置也可能导致服务端解析失败。

修复方案

直接修改序列化对象结构,删除外层的fields包装,同时移除多余的请求头设置即可,修正后的代码如下:

public async Task UpdateSharePointListItem(string webApiUrl, string itemId, string scheduledTimeSlot, string accessToken)
{
    Console.WriteLine(itemId);
    Console.WriteLine(scheduledTimeSlot);
    // 直接构造字段字典,不需要外层fields
    var fields = new Dictionary<string, string>
    {
        { "ScheduledTimeSlot", scheduledTimeSlot }
    };
    string addItemJsonString = JsonConvert.SerializeObject(fields);
    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);
    // 这里已经设置了正确的Content-Type,不需要额外添加
    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);
}

内容的提问来源于stack exchange,提问作者user8779054

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:24:03