如何从C#控制台应用程序发送通知

11 浏览
0 Comments

如何从C#控制台应用程序发送通知

我想创建一个控制台应用程序,用于通过Google Firebase通知向不同的移动设备发送通知,

我从链接Send push to Android by C# using FCM (Firebase Cloud Messaging)看到了代码。

我得到了状态码为500的内部服务器错误。

try{
    string url = @"https://fcm.googleapis.com/fcm/send";
    WebRequest tRequest = WebRequest.Create(url);
    tRequest.Method = "post";
    tRequest.ContentType = "application/json";
    string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + "This is the message" + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + "";
    var data = new
    {
        to = deviceId,
        notification = new
        {
            body = "This is the message",
            title = "This is the title"
        }
    };
    string jsonss = Newtonsoft.Json.JsonConvert.SerializeObject(data);
    Byte[] byteArray = Encoding.UTF8.GetBytes(jsonss);              
    tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
    tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
    tRequest.ContentLength = byteArray.Length;
    tRequest.ContentType = "application/json";
    using (Stream dataStream = tRequest.GetRequestStream())
    {
        dataStream.Write(byteArray, 0, byteArray.Length);
        using (WebResponse tResponse = tRequest.GetResponse())
        {
            using (Stream dataStreamResponse = tResponse.GetResponseStream())
            {
                using (StreamReader tReader = new StreamReader(dataStreamResponse))
                {
                    String sResponseFromServer = tReader.ReadToEnd();
                    Console.Write(sResponseFromServer);
                }
            }
        }
    }
}
catch (Exception ex)
{
    Console.Write(ex.Message);
    {
        var sss = ex.Message;
        if (ex.InnerException != null)
        {
            var ss = ex.InnerException;
        }
    }
}

0
0 Comments

问题出现的原因是变量"applicationID"使用了错误的值,实际上使用了mobilesdk_app_id的值而不是当前的api_key密钥,这就是为什么会出现500错误。解决方法是使用正确的api_key值。代码如下:

// 使用正确的api_key值
string applicationID = "api_key";
// 其他代码...

感谢Json和Francis Lord的帮助,问题已经解决。

0
0 Comments

如何从C#控制台应用程序发送通知

在使用C#发送通知的代码中,我已经使其工作正常。代码如下:

WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var objNotification = new
{
    to = notification.DeviceToken,
    data = new
    {
        title = notification.NotificationTitle,
        body = notification.NotificationBody
    }
};
string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(objNotification);
Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat);
tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
tRequest.ContentType = "application/json";
using (Stream dataStream = tRequest.GetRequestStream())
{
    dataStream.Write(byteArray, 0, byteArray.Length);
    
    using (WebResponse tResponse = tRequest.GetResponse())
    {
        using (Stream dataStreamResponse = tResponse.GetResponseStream())
        {
            using (StreamReader tReader = new StreamReader(dataStreamResponse))
            {
                String responseFromFirebaseServer = tReader.ReadToEnd();
                FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject(responseFromFirebaseServer);
                
                if (response.success == 1)
                {
                    new NotificationBLL().InsertNotificationLog(dayNumber, notification, true);
                }
                else if (response.failure == 1)
                {
                    new NotificationBLL().InsertNotificationLog(dayNumber, notification, false);
                    sbLogger.AppendLine(string.Format("Error sent from FCM server, after sending request : {0} , for following device info: {1}", responseFromFirebaseServer, jsonNotificationFormat));
                }
            }
        }
    }
}

上述代码中使用的FCMResponse类用于存储从FCM服务器返回的响应。代码如下:

public class FCMResponse
{
    public long multicast_id { get; set; }
    public int success { get; set; }
    public int failure { get; set; }
    public int canonical_ids { get; set; }
    public List results { get; set; }
}
public class FCMResult
{
    public string message_id { get; set; }
}

FCMResult类是用于存储FCM服务器返回的结果的。如果需要FCMResult类的代码,请参考以下代码:

public class FCMResult
{
    // 添加FCMResult类的属性
}

以上是关于如何从C#控制台应用程序发送通知的代码和相关类。希望对您有所帮助!

0