C# 当我使用.NET Core HttpClient时,Google FCM给了我一个坏请求

C# 当我使用.NET Core HttpClient时,Google FCM给了我一个坏请求,c#,.net-core,firebase-cloud-messaging,dotnet-httpclient,C#,.net Core,Firebase Cloud Messaging,Dotnet Httpclient,我正在尝试使用FCMAPI在android应用程序上发送推送通知。如果我使用一些HTTP客户端,比如失眠或邮递员,效果会很好。屏幕如下所示: 和标题: 当然,我有注册ID和FCM服务器密钥,而不是xxx 但是我需要从我的C#code发送相同的代码。我总是有不良请求。我不明白为什么 这是我的密码: var json = JsonConvert.SerializeObject(new { to = customer.FcmRegistrationId, notification

我正在尝试使用FCMAPI在android应用程序上发送推送通知。如果我使用一些HTTP客户端,比如失眠或邮递员,效果会很好。屏幕如下所示:

和标题:

当然,我有注册ID和FCM服务器密钥,而不是
xxx

但是我需要从我的
C#
code发送相同的代码。我总是有不良请求。我不明白为什么

这是我的密码:

var json = JsonConvert.SerializeObject(new
{
    to = customer.FcmRegistrationId,
    notification = new
    {
        body = push.PushBody,
        title = push.PushTitle,
        sound = "default"
    }
});

var content = new StringContent(json, Encoding.UTF8, "application/json");

var request = new HttpRequestMessage
{
    RequestUri = new Uri("https://fcm.googleapis.com/fcm/send"),
    Content = content,
};

request.Headers.TryAddWithoutValidation("Authorization", 
    "key=" + customer.FCMServerKey);

HttpResponseMessage response;

using (var client = new HttpClient())
{
    response = await client.SendAsync(request);
}

response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync(); 
正如我之前所悲伤的,我总是有这样的答案:


请帮帮我

我测试了一种发送推送通知的方法:使用WebRequest.Create

请在fcm注册设备上设置设备id(您的注册id)、服务器API密钥和fcm帐户的发送者id

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace SendMsgByFCM
{
    public partial class Form1 : Form
    {

        AndroidGCMPushNotification fcmPush = new AndroidGCMPushNotification();


        public Form1()
        {
            InitForm();
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
             **devId** = "faxgYiWv4Sk:APA91bGehlGNNGaE20djfaJ5xzQst_b190GvrEwm_yvPsZvY-.....";
            fcmPush.SendNotification(devId, 'message ...' );
            MessageBox.Show( "msg send" );
        }
    }

    public class AndroidGCMPushNotification
    {

        public string SendNotification(string deviceId, string message)
        {
            string **SERVER_API_KEY** = "AAAADtSR7s8:APA91bHhhsjRMeL2gH6Qzv5BbdJyshOtgJ-J....";

            var **SENDER_ID** = "636988888888";
            var value = message;
            WebRequest tRequest;
            tRequest = **WebRequest.Create**("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));

            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

            string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
            Console.WriteLine(postData);
            Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            tRequest.ContentLength = byteArray.Length;

            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse tResponse = tRequest.GetResponse();

            dataStream = tResponse.GetResponseStream();

            StreamReader tReader = new StreamReader(dataStream);

            String sResponseFromServer = tReader.ReadToEnd();


            tReader.Close();
            dataStream.Close();
            tResponse.Close();
            return sResponseFromServer;
        }
    }
}

我通过以下代码解决了这个问题:

using (var client = new HttpClient())
{

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"key={ServerKey}");
var obj = new
{
    to = Id,
    notification = new
    {
        title = Title,
        body = Message

    }
};

//serialize object data to json
string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
// create an http string content
var data = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://fcm.googleapis.com/fcm/send", data);
return response.StatusCode;

...
完整的来源在这里


我不知道为什么,但是原始源代码中的
数据
文本
不起作用。使用
title
body

您可以添加一个类似fiddler的代理来检查这两个有效负载吗?这就是我的出发点。添加代理并检查标题、正文等谢谢。我试试看。我以前从未使用过它。错误的请求几乎总是在有效负载的一个或多个字段上输入错误。请记住,序列化将导致发送字段中出现一对一的变量。因此,请检查您的类成员名称,以确保它映射了邮递员负载。我已检查了所有字段。我已经将json转储并将其放入
http客户机。我对服务器身份验证密钥也做了同样的操作。一切都好!然后,您需要检查Http客户端创建的确切负载,以便弄清楚这一点(fiddler或类似的东西)。是WinForms吗?它是否适用于.NET核心Web Api?