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

C# Google Admin SDK Update接口空属性意外清空及ModifyRequest使用咨询

解决方案

方案1:优先使用Patch请求(推荐)

你的需求是仅更新已赋值的字段、避免null字段触发清空逻辑,直接使用SDK提供的Patch方法即可原生满足,无需额外处理请求体:

public User UpdateUser(Google.Apis.Admin.Directory.directory_v1.Data.User gUser)
{
    UsersResource.PatchRequest patchRequest = _service.Users.Patch(gUser, gUser.Id);
    User updatedUser = patchRequest.Execute();
    return updatedUser;
}

Patch方法天生不会将未赋值的null属性序列化到请求体中,和你需要的逻辑完全匹配,是成本最低的解决方案。

方案2:通过ModifyRequest修改Update请求体

如果你必须使用Update方法,可以通过ModifyRequest钩子在请求发送前过滤掉null字段,具体用法如下:
ModifyRequest是SDK暴露的请求预处理委托,SDK构造完完整HTTP请求后、发送到服务器前,会执行你传入的委托,你可以在委托内修改请求的任意内容。示例代码:

using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;

public User UpdateUser(Google.Apis.Admin.Directory.directory_v1.Data.User gUser)
{
    UsersResource.UpdateRequest userUpdateRequest = _service.Users.Update(gUser, gUser.Id);
    
    userUpdateRequest.ModifyRequest = async (request) =>
    {
        // 读取原始请求JSON
        string originalBody = await request.Content.ReadAsStringAsync();
        JObject bodyJson = JObject.Parse(originalBody);
        
        // 移除所有值为null的属性(如果有需要主动清空的字段,可在此处加过滤条件排除)
        var nullProps = bodyJson.Descendants()
            .OfType<JProperty>()
            .Where(p => p.Value.Type == JTokenType.Null)
            .ToList();
        foreach (var prop in nullProps)
        {
            prop.Remove();
        }
        
        // 替换请求体
        request.Content = new StringContent(bodyJson.ToString(), Encoding.UTF8, "application/json");
    };
    
    User updatedUser = userUpdateRequest.Execute();
    return updatedUser;
}

注:代码依赖Newtonsoft.Json,和Google .NET SDK默认使用的序列化库一致,无兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:24:03