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

使用Microsoft Graph SDK for .NET创建SharePoint列表项时遇ODataError

解决Microsoft Graph SDK for .NET创建SharePoint列表项400错误问题

问题分析

直接调用Graph API成功但SDK失败,通常是SDK对字段类型的序列化要求更严格,尤其是查找字段、用户字段、日期字段这类特殊类型,你的代码里可能存在类型不匹配的问题。另外,默认的ODataError只抛出泛型异常,需要捕获详细错误信息定位具体问题。

解决方案

1. 捕获详细错误信息定位问题

修改代码捕获ODataError的具体错误内容,明确哪个字段格式不符合要求:

try
{
    await this.graphClient.Sites[this.SiteId].Lists[listId].Items.PostAsync(listItem);
}
catch (Microsoft.Graph.Models.ODataErrors.ODataError odataError)
{
    Console.WriteLine($"错误提示: {odataError.Error.Message}");
    if (odataError.Error.Details != null)
    {
        foreach (var detail in odataError.Error.Details)
        {
            Console.WriteLine($"字段错误: {detail.Message}");
        }
    }
}

2. 修正特殊字段的类型格式

针对SharePoint列表的特殊字段,调整代码中的数据类型,匹配SDK的序列化规则:

var itemDictionary = new Dictionary<string, object>()
{
    { "Tenant", "100" },
    { "LicenseLookupId", 1 }, // 查找字段ID改为int类型(原代码传字符串"1"不符合SDK序列化要求)
    { "Quantity", 10 },
    { "Requester", new { Email = "test@test.am" } }, // 用户字段用包含Email的对象结构
    { "RequestDate", new DateTime(2023, 8, 22) }, // 日期字段传DateTime类型,SDK自动处理格式
    { "Status", "In Progress" }
};

var listItem = new ListItem
{
    Fields = new FieldValueSet
    {
        AdditionalData = itemDictionary
    }
};

// 执行创建
await this.graphClient.Sites[this.SiteId].Lists[listId].Items.PostAsync(listItem);

补充说明

  • 如果用户字段需要绑定已存在的站点用户,也可以使用@odata.bind格式:
    { "Requester@odata.bind": $"https://graph.microsoft.com/v1.0/sites/{this.SiteId}/siteUsers('test@test.am')" }
    
  • 确保所有字段名称是SharePoint列表的内部名称(而非显示名称),虽然你API调用成功已验证,但如果后续仍有问题可以检查这一点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:06:20