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

使用Refit(C# WPF)向Firestore发送PATCH请求更新单字段时遇400错误

排查Firebase文档单个属性更新的400错误(Refit C#实现)

问题场景

使用Refit实现Patch请求更新Firebase文档的licence属性时返回400错误,核心代码如下:

[Patch("/projects/super-project-name/databases/(default)/documents/users/{userId}?updateMask.fieldPaths=licence")]
public Task UpdateUserLicence3(string userId, [Body] Fields licence);

已知前置信息:

  • 移除[Body] Fields licence参数后,请求可正常删除licence字段;
  • 查询单个用户的GET接口工作正常。

排查与修复方案

1. 修正请求体的结构格式

Firebase REST API要求更新文档的请求体必须包含fields顶级键,而非直接传入字段对象。如果你的Fields类没有做这个包装,序列化后的请求体不符合API规范,会触发400错误。

步骤:

  • 创建请求体包装类:
public class UpdateDocumentRequest
{
    public Fields fields { get; set; }
}
  • 修改Refit接口:
[Patch("/projects/super-project-name/databases/(default)/documents/users/{userId}?updateMask.fieldPaths=licence")]
public Task UpdateUserLicence3(string userId, [Body] UpdateDocumentRequest request);

2. 匹配Firebase字段类型定义

Firebase要求每个字段值必须指定类型(如stringValue、integerValue等),若Fields类未正确定义这些属性,同样会导致请求格式错误。

示例定义:

public class Fields
{
    public StringValue licence { get; set; }
}

public class StringValue
{
    public string stringValue { get; set; }
}

使用方式:

var updateRequest = new UpdateDocumentRequest
{
    fields = new Fields
    {
        licence = new StringValue { stringValue = "your-new-licence" }
    }
};
await api.UpdateUserLicence3(userId, updateRequest);

3. 优化updateMask的传递方式

直接在URL中拼接updateMask.fieldPaths=licence可能存在编码问题,建议通过查询参数传递,让Refit自动处理编码:

[Patch("/projects/super-project-name/databases/(default)/documents/users/{userId}")]
public Task UpdateUserLicence3(string userId, [Body] UpdateDocumentRequest request, [Query(Name = "updateMask.fieldPaths")] string fieldPath = "licence");

4. 获取详细错误信息定位问题

捕获Refit的ApiException,提取响应内容查看Firebase返回的具体错误描述,能快速定位问题:

try
{
    await api.UpdateUserLicence3(userId, updateRequest);
}
catch (ApiException ex)
{
    var errorDetails = await ex.GetContentAsStringAsync();
    // 输出errorDetails查看具体错误原因
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:01:16