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

How to send notification from C# Console application(如何从 C# 控制台应用程序发送通知)
本文介绍了如何从 C# 控制台应用程序发送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我从链接中看到了代码

这是使用 C# 发送通知的代码,我已经让它工作了

 WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");tRequest.Method = "发布";tRequest.ContentType = "应用程序/json";var objNotification = 新{to = notification.DeviceToken,数据=新{标题 = 通知.通知标题,正文 = 通知.NotificationBody}};字符串 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 = "应用程序/json";使用(流数据流 = tRequest.GetRequestStream()){dataStream.Write(byteArray, 0, byteArray.Length);使用 (WebResponse tResponse = tRequest.GetResponse()){使用(流数据流响应 = tResponse.GetResponseStream()){使用 (StreamReader tReader = new StreamReader(dataStreamResponse)){字符串 responseFromFirebaseServer = tReader.ReadToEnd();FCMResponse 响应 = Newtonsoft.Json.JsonConvert.DeserializeObject(responseFromFirebaseServer);如果 (response.success == 1){new NotificationBLL().InsertNotificationLog(dayNumber, notification, true);}否则如果(response.failure == 1){new NotificationBLL().InsertNotificationLog(dayNumber, notification, false);sbLogger.AppendLine(string.Format("FCM 服务器发送的错误,发送请求后:{0},对于以下设备信息:{1}", responseFromFirebaseServer, jsonNotificationFormat));}}}}}

这是代码中用于存储从 FMServer 发送的响应的 FCMResponse 类

 公共类 FCMResponse{public long multicast_id { 获取;放;}公共 int 成功 { 获取;放;}公共 int 失败 { 获取;放;}公共 int canonical_ids { 获取;放;}公共列表<FCMResult>结果{得到;放;}}公共类 FCMResult{公共字符串 message_id { 获取;放;}}

I want to create console application which is used to send notifications to different mobile devices via Goolge Firebase Notifications,

I have seen the code from link Send push to Android by C# using FCM (Firebase Cloud Messaging)

I am getting internal server error with status code 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() + "&registration_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;
        }
    }

}

解决方案

Here is the code to send notification using C#, I have made it working

 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<FCMResponse>(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));

                                        }

                                    }
                                }

                            }
                        }

Here is class FCMResponse used in this code to store response sent from FMServer

 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<FCMResult> results { get; set; }
}
  public class FCMResult
{
    public string message_id { get; set; }
}

这篇关于如何从 C# 控制台应用程序发送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)