离子推送通知API在C#中使用的WebAPI [英] Ionic push notification api in c# with WebApi
问题描述
我试图发送使用离子推送通知API推送通知,使用C#与的WebAPI。
从离子网站蟒的例子是可以正常使用的,但我不能让它工作在C#,尽管它似乎要求是相同的。
这是我的code:
I'm trying to send a push notification using the ionic push notifications api, using c# with WebApi. The python example from ionic website is working perfectly, but I can't get it working in c#, although it seems that the requests are the same. This is my code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://push.ionic.io/api/v1/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("X-Ionic-Application-Id", IONIC_APP_ID);
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var keyBase64 = "Basic " + IONIC_PRIVATE_KEY_BASE_64;
client.DefaultRequestHeaders.Add("Authorization", keyBase64);
client.DefaultRequestHeaders.Add("Accept-Encoding", "identity");
//client.DefaultRequestHeaders.Add("Content-Type", "application/json");
var response = client.PostAsJsonAsync("push", json).Result;
if (response.IsSuccessStatusCode)
{
int a = 6;
}
}
我不断收到错误的请求(400),没有进一步的解释。
I keep getting bad request (400), with no further explanation.
推荐答案
确定,解决它!
问题是与Content-Type头的PostAsJsonAsync方式默认内容类型是应用/ JSON的;字符集= UTF-8,而API期待应用/ JSON
OK, solved it! The problem was with the Content-Type header, the "PostAsJsonAsync" method default content-type is "application/json; charset=utf-8", while the api is expecting "application/json".
本作品:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(API_URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("X-Ionic-Application-Id", IONIC_APP_ID);
var keyBase64 = "Basic " + IONIC_PRIVATE_KEY_BASE_64;
client.DefaultRequestHeaders.Add("Authorization", keyBase64);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, api);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
var response = client.SendAsync(request).Result;
}
有关的清晰度,调用函数是:
For clarity, the calling function is :
public void Send(string regId, string msg, int notificationId)
{
dynamic data = new ExpandoObject();
data.tokens = new List<string>() {regId};
data.notification = new ExpandoObject() as dynamic;
data.notification.alert = msg;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
log.InfoFormat("Sending notifcation to {0}, message is {1} ", regId, msg);
SendToIonic("push", json);
}
这篇关于离子推送通知API在C#中使用的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!