![](/img/trans.png)
[英]Firebase asp.net push notifications works locally but not deployed
[英]Notifications not sending on ASP.NET MVC
我從我的 ASP.NET MVC 項目發送通知,但現在我不能再發送它們了。 我收到不匹配的發件人 ID 錯誤。 我檢查了我的發件人 ID,它是正確的。
示例響應
{
"multicast_id": 5340432438815499122,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [ {"error":"MismatchSenderId"} ]
}
我正在使用這段代碼;
public string ExecutePushNotification(string title, string msg, string fcmToken, object data)
{
var serverKey = "AAAAxxxx ";
var senderId = "xxxxxx";
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
httpWebRequest.ContentType = "application/x-www-urlencoded";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
notification = new
{
title = title,
body = msg,
sound = "default"
},
data = new
{
info = data
},
to = fcmToken,
priority = "high",
content_available = true,
};
var serializer = new JavaScriptSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = serializer.Serialize(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
有什么建議么?
我通過為 ASP.NET 和 google.json 文件添加 Firebase Admin package 來修復它。
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; }
}
public string ExecutePushNotification(string title, string msg, string fcmToken, object data)
{
if (FirebaseApp.DefaultInstance == null)
{
var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "google-services.json");
var defaultApp = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "varmallapp-firebase-adminsdk-9yv7a-46e9351df3.json")),
});
}
else
{
var defaultApp = FirebaseApp.DefaultInstance;
}
// Console.WriteLine(defaultApp.Name); // "[DEFAULT]"
var message = new FirebaseAdmin.Messaging.Message()
{
Data = new Dictionary<string, string>()
{
["Date"] = DateTime.Now.ToString(),
["User"] = "VARBAZAR"
},
Notification = new FirebaseAdmin.Messaging.Notification
{
Title = title,
Body = msg
},
Token = fcmToken
};
var messaging = FirebaseMessaging.DefaultInstance;
var result = messaging.SendAsync(message);
//Console.WriteLine(result); //projects/myapp/messages/2492588335721724324
return result.ToString();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.