Send Notifications using OneSignal

Jassim Al Rahma 1,556 Reputation points
2021-11-27T22:09:11.727+00:00

Hi,

How can I send notifications using OneSignal and HttpClient?

From the below link:

https://documentation.onesignal.com/reference/create-notification#example-code---create-notification

I tried this code but did not work:

var client = new HttpClient();

client.BaseAddress = new Uri("https://onesignal.com/api/v1/notifications");
client.DefaultRequestHeaders.Add("authorization", "Basic " + onesignalUserAuth);

var content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("app_id", SecureStorage.GetAsync("AppID").Result),
    new KeyValuePair<string, string>("contents[en]", EditorMessage.Text.Trim()),
    new KeyValuePair<string, string>("included_segments", "All")
});

var response = await client.PostAsync("https://onesignal.com/api/v1/notifications", content);

Kindly help..

Thanks,
Jassim

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,326 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,650 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,496 Reputation points
    2021-11-27T22:33:56.113+00:00

    It looks like that endpoint accepts JSON rather than form-urlencoded content. If you try this instead does it work?:

    var client = new HttpClient();
    
    client.BaseAddress = new Uri("https://onesignal.com/api/v1/notifications");
    client.DefaultRequestHeaders.Add("authorization", "Basic " + onesignalUserAuth);
    client.DefaultRequestHeaders.Add("Content-Type", "application/json");
    
    var content = new StringContent(JsonSerializer.Serialize(new {
        app_id = SecureStorage.GetAsync("AppID").Result,
        contents = new {
            en = EditorMessage.Text.Trim()
        },
        included_segments = "All"
    }));
    
    var response = await client.PostAsync("https://onesignal.com/api/v1/notifications", content);
    

0 additional answers

Sort by: Most helpful