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

迁移至FCM API V1发送消息时400错误的解决方法

FCM API V1迁移400 Bad Request问题排查

你在从旧版FCM迁移到V1 API时遇到400错误,以下是核心问题点及修正建议:

1. JSON负载结构不符合V1规范

FCM V1要求请求体必须将所有内容包裹在message字段下,你的代码直接把token放在顶层,这是导致400错误的最可能原因。修正后的结构如下:

body = new
{
    message = new
    {
        token = pushToken,
        notification = new
        {
            title = "Patient Flow",
            body = message,
            sound = soundFileName
        },
        data = new
        {
            type = notificationType
        }
    }
};

2. 异步操作未正确等待

代码中使用await获取访问令牌,但如果当前方法未标记为async Task<bool>,会导致令牌还未获取完成就执行后续请求,可能拿到空令牌。需确保方法签名为public async Task<bool> SendNotification(...)。

3. 缺失错误详情捕获

当前代码未捕获WebException并读取响应体的错误信息,FCM的400响应会返回具体的错误原因(如字段格式错误、项目ID不匹配等)。添加错误捕获逻辑:

try
{
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        string httpResult = streamReader.ReadToEnd();
        if (httpResponse.StatusCode != HttpStatusCode.OK)
        {
            Logger.Write(TraceTyp.DEBUG, String.Empty, "PushNotificationProcessor.SendNotification", $"推送未成功,响应:{httpResult}", String.Empty);
        }
    }
}
catch (WebException ex)
{
    using (var errorResponse = (HttpWebResponse)ex.Response)
    {
        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
        {
            string errorDetails = reader.ReadToEnd();
            Logger.Write(TraceTyp.DEBUG, String.Empty, "PushNotificationProcessor.SendNotification", $"推送失败,错误详情:{errorDetails}", String.Empty);
        }
    }
}

4. 端点URL项目ID未替换

确认端点URL中的myproject-id已替换为实际的Firebase项目ID,需与服务账号JSON文件中的项目ID完全一致。

5. 序列化工具建议

JavaScriptSerializer是老旧组件,建议替换为Newtonsoft.Json或System.Text.Json,避免序列化格式问题:

// 使用Newtonsoft.Json的示例
string json = JsonConvert.SerializeObject(body);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:28:22