Send Push Notification using C# and OneSignal

Here is a sample code using C# to send a push notification to your mobile application using the OneSignal API. Create a free account on https://onesignal.com/ and get your OneSignal AppID and OneSignal RestID keys.

I use the below C# code in a console app to send OneSignal push notifications to Xamarin Forms apps using the OneSignal Nuget https://www.nuget.org/packages/Com.OneSignal/
You can use this code in a Windows Service, Web API, ASP.NET / MVC Web app, etc…

See my PHP example here

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
OneSignalSender();
}

private static void OneSignalSender()
{
string onesignalAppID = "your-onesignalAppID"; 
string onesignalRestID = "your-onesignalRestID "; 

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic " + onesignalRestID);

var userid = 123;
string message = "this is the message";

var contentsMessage = new { en = message };

//if using filters
var filtersField = new {
field = "tag",
key = "userid",
relation = "=",
value = userid
};

//if using segments
List<string> segmentsEnum = new List<string>()
{
//"Subscribed Users"
"test users"
};

List<object> filtersEnum = new List<object>();
filtersEnum.Add(filtersField);

var obj = new
{
app_id = onesignalAppID,
contents = contentsMessage,
//filters = filtersEnum, //uncomment if using filters
//included_segments = segmentsEnum //uncomment if using segments
};

var json = JsonConvert.SerializeObject(obj);

byte[] byteArray = Encoding.UTF8.GetBytes(json);

string responseContent = null;

try
{
using (var writer = request.GetRequestStream())
{
writer.Write(byteArray, 0, byteArray.Length);
}

using (var response = request.GetResponse() as HttpWebResponse)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}

System.Diagnostics.Debug.WriteLine(responseContent);
}}
}