带有WebApi的c#中的Ionic推送通知api

本文关键字:通知 api Ionic 中的 WebApi 带有 | 更新日期: 2023-09-27 18:21:28

我正在尝试使用ionic推送通知api,使用c#和WebApi发送推送通知。ionic网站上的python示例运行得很好,但我无法让它在c#中运行,尽管请求似乎是一样的。这是我的代码:

 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),没有进一步的解释。

带有WebApi的c#中的Ionic推送通知api

好的,解决了!问题出在Content-Type标头上,"PostAsJsonAsync"方法的默认内容类型为"application/json;charset=utf-8",而api则要求为"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;                
        }

为了清楚起见,调用函数为:

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);           
    }

以下是您的操作方法:

[HttpGet]
    [Route("A_Test")]
    public HttpResponseMessage A_Test()
    {
        HttpResponseMessage response;
        try
        {
            string regId = "";
            string profile = "<Name of Security Profile>";
            string msg = "Test";
            string data = "{ '"tokens'":[],'"send_to_all'":" + "true" + ",'"profile'":'"" + profile + "'",'"notification'":{'"message'":'"" + msg + "'"}}";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://api.ionic.io/push/notifications");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Add("X-Ionic-Application-Id", "<Ionic App ID>");
                var keyBase64 = "Bearer " + "<Security Token>";
                client.DefaultRequestHeaders.Add("Authorization", keyBase64);
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://api.ionic.io/push/notifications");
                request.Content = new StringContent(data, Encoding.UTF8, "application/json");
                response = new HttpResponseMessage(HttpStatusCode.OK);
                response = client.SendAsync(request).Result;
            }
            return response;
        }
        catch (Exception ex)
        {
            response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            response.Content = new ObjectContent(typeof(string), ex.Message, new JsonMediaTypeFormatter(), "application/json");
            return response;
        }
    }

我使用过RestClient:

public async Task Send(string userId, string devicePushToken, string content)
{
    string json = JsonConvert.SerializeObject(new
    {
        tokens = new[] {devicePushToken},
        profile = "yourprofile",
        notification = new
        {
            message = content
        }
    });
    var restClient = new RestClient("https://api.ionic.io/");
    var restRequest = new RestRequest("push/notifications", Method.POST);
    restRequest.AddHeader("Accept", "application/json");
    restRequest.AddParameter("application/json", json, ParameterType.RequestBody);
    restRequest.AddParameter("Authorization",
        "Bearer APIKEY",
        ParameterType.HttpHeader);
    await restClient.ExecuteTaskAsync(restRequest);
}