FCM (Firebase Cloud Messaging) Push Notification with Asp.Net

前端 未结 7 998
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 22:01

I have already push the GCM message to google server using asp .net in following method,

GCM Push Notification with Asp.Net

<
相关标签:
7条回答
  • 2020-11-28 22:58

    To hit Firebase API we need some information from Firebase, we need the API URL (https://fcm.googleapis.com/fcm/send) and unique keys that identify our Firebase project for security reasons.

    We can use this method to send notifications from .NET Core backend:

            public async Task<bool> SendNotificationAsync(string token, string title, string body)
        {
            using (var client = new HttpClient())
            {
                var firebaseOptionsServerId = _firebaseOptions.ServerApiKey;
                var firebaseOptionsSenderId = _firebaseOptions.SenderId;
    
                client.BaseAddress = new Uri("https://fcm.googleapis.com");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",
                    $"key={firebaseOptionsServerId}");
                client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", $"id={firebaseOptionsSenderId}");
    
    
                var data = new
                {
                    to = token,
                    notification = new
                    {
                        body = body,
                        title = title,
                    },
                    priority = "high"
                };
    
                var json = JsonConvert.SerializeObject(data);
                var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
    
                var result = await _client.PostAsync("/fcm/send", httpContent);
                return result.StatusCode.Equals(HttpStatusCode.OK);
            }
        }
    

    These parameters are:

    • token: string represents a FCM token provided by Firebase on each app-installation. This is going to be the list of app-installations that the notification is going to send.
    • title: It’s the bold section of notification.
    • body: It represents “Message text” field of the Firebase SDK, this is the message you want to send to the users.

    To find your Sender ID and API key you have to:

    • Login to the Firebase Developer Console and go to your Dashboard
    • Click on the “gear” icon and access “project settings”
    • Go to the “Cloud Messaging Section” and you will have access to the sender ID and the API Key.
    0 讨论(0)
提交回复
热议问题