Fire base documentation for register:
Model declaration:
public class PushNotificationModel
{
public PushNotificationModel()
{
notification = new NotificaitonModel();
data = new DataNotificationModel();
}
public string[] registration_ids { get; set; }
public string priority { get; set; }
public NotificaitonModel notification { get; set; }
public DataNotificationModel data { get; set; }
}
public class NotificaitonModel
{
public string title { get; set; }
public string body { get; set; }
}
public class DataNotificationModel
{
public DateTime Date { get; set; }
public string Message { get; set; }
public bool IsExceedLimit { get; set; }
}
Controller or Service:
{
private static string serverApiKey = "Register Project API key";
public string SendNotification(PushNotificationModel model)
{
try
{
WebRequest tRequest = WebRequest.Create(https://fcm.googleapis.com/fcm/send);
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization:key={0}", serverApiKey));
var json = JsonConvert.SerializeObject(model);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
if (byteArray.Length > 4000)
{
model.data = new DataNotificationModel();
model.data.IsExceedLimit = true;
json = JsonConvert.SerializeObject(model);
byteArray = Encoding.UTF8.GetBytes(json);
}
tRequest.ContentLength = byteArray.Length;
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();
return sResponseFromServer;
}
}
}
}
}
catch (Exception e)
{
return "";
}
}
public static string ConvertJson(List<string> RegistrationIds)
{
return JsonConvert.SerializeObject(RegistrationIds);
}
}
Function Call:
PushNotificationModel pushNotificationModel = new PushNotificationModel()
{
registration_ids = new string[] { "FIREBASE REG USER ID"},
priority = "high",
notification = new NotificaitonModel()
{
title = "sample notification",
body = "body content here"
},
data = new DataNotificationModel()
{
Date = DateTime.UtcNow,
Message = "Your message content"
}
};
new PushNotification().SendNotification(pushNotificationModel);
No comments:
Post a Comment