Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. OneSignal Push Notification Integration in ASP.NET Core Web API

OneSignal Push Notification Integration in ASP.NET Core Web API

Date- Apr 27,2026 87
onesignal push notifications

Overview

Push notifications are messages sent from a server to a user's device, providing updates, alerts, or reminders. They are essential for maintaining user engagement, especially in mobile and web applications. OneSignal is a powerful service that simplifies the process of sending push notifications across platforms, including web and mobile.

The core purpose of OneSignal is to enable developers to communicate with users effectively, ensuring they receive important information even when the application is not actively in use. A real-world use case could be an e-commerce application that sends notifications about order status, promotions, or new product arrivals, significantly enhancing user experience and retention.

Prerequisites

  • ASP.NET Core SDK: Ensure you have the latest version of the ASP.NET Core SDK installed on your machine.
  • OneSignal Account: Sign up for a free OneSignal account to get access to the API keys and configurations needed for integration.
  • Basic Knowledge of REST APIs: Familiarity with RESTful principles will help you understand the endpoints and data flow.
  • NuGet Package Manager: You'll need to manage packages for your ASP.NET Core project.

Setting Up OneSignal

To start using OneSignal for push notifications, you need to create a new app on the OneSignal dashboard. This process involves logging into your OneSignal account, navigating to the dashboard, and selecting 'Add App'. You'll be prompted to choose the platform for your app, such as Web Push, iOS, or Android.

Once the app is created, you will receive the App ID and REST API Key. These credentials are crucial for authenticating requests from your ASP.NET Core application to the OneSignal service. Store these securely in your application settings or environment variables to keep them safe from unauthorized access.

public class OneSignalSettings
{
    public string AppId { get; set; }
    public string ApiKey { get; set; }
}

This class serves to encapsulate the OneSignal configuration settings. You'll use this settings class to bind the configuration values from your app settings.

Configuring the Application

Next, you need to configure your ASP.NET Core application to use the OneSignal settings. This involves adding the settings to your appsettings.json file and binding them in the Startup class.

// appsettings.json
{
  "OneSignal": {
    "AppId": "your-onesignal-app-id",
    "ApiKey": "your-onesignal-rest-api-key"
  }
}
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.Configure(Configuration.GetSection("OneSignal"));
    services.AddHttpClient();
    services.AddControllers();
}

The first code block illustrates how to store your OneSignal credentials in the configuration file. The second block demonstrates how to bind these settings in the ConfigureServices method of the Startup class. The AddHttpClient method is crucial for making HTTP requests to the OneSignal API.

Sending Notifications

To send notifications using OneSignal, you will create an HTTP client service that encapsulates the logic for constructing and sending requests to the OneSignal API. This service will utilize the credentials provided in the configuration.

public class OneSignalService
{
    private readonly HttpClient _httpClient;
    private readonly OneSignalSettings _settings;

    public OneSignalService(IHttpClientFactory httpClientFactory, IOptions options)
    {
        _httpClient = httpClientFactory.CreateClient();
        _settings = options.Value;
    }

    public async Task SendNotificationAsync(string message, List playerIds)
    {
        var requestBody = new
        {
            app_id = _settings.AppId,
            included_segments = new[] { "All" },
            include_external_user_ids = playerIds,
            contents = new { en = message }
        };
        var json = JsonSerializer.Serialize(requestBody);
        var request = new HttpRequestMessage(HttpMethod.Post, "https://onesignal.com/api/v1/notifications")
        {
            Content = new StringContent(json, Encoding.UTF8, "application/json")
        };
        request.Headers.Add("Authorization", "Basic " + _settings.ApiKey);
        var response = await _httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();
    }
}

This code defines a service class that takes advantage of dependency injection to manage the HTTP client and OneSignal settings. The SendNotificationAsync method constructs the payload for the notification and sends it to the OneSignal API.

Understanding the Code

  • HttpClient: The service uses IHttpClientFactory to create an instance of HttpClient, promoting better resource management.
  • Request Body: The payload includes the app ID, the segments or user IDs to target, and the content of the notification.
  • Authorization Header: The API key is added to the request headers for authentication.
  • Response Handling: The EnsureSuccessStatusCode method throws an exception if the request fails, allowing for error handling.

Receiving Notifications in the Client

Once notifications are sent, the client-side application must be set up to receive them. For web applications, this typically involves registering a service worker and using the OneSignal SDK.

// In your client-side JavaScript
OneSignal.push(function() {
    OneSignal.init({
        appId: 'your-onesignal-app-id',
    });
    OneSignal.registerForPushNotifications();
});

This JavaScript code initializes OneSignal and registers the user's device for push notifications. The app ID is essential for linking the client to the OneSignal dashboard.

Service Worker Registration

In addition to the initialization, a service worker must be registered to handle incoming push notifications. This can be done by creating a service worker file.

// service-worker.js
self.addEventListener('push', function(event) {
    const data = event.data ? event.data.json() : {};
    const title = data.headings ? data.headings.en : 'Notification';
    const options = {
        body: data.contents.en,
        icon: 'icon.png'
    };
    event.waitUntil(
        self.registration.showNotification(title, options)
    );
});

This service worker listens for push events and displays notifications using the browser's notification API. The waitUntil method ensures that the notification display completes before the event is considered finished.

Edge Cases & Gotchas

When working with push notifications, several edge cases can arise. One common pitfall is failing to handle errors during the notification sending process properly. If the OneSignal API responds with an error, such as invalid player IDs or missing fields, your application should log the error and provide feedback to the user.

public async Task SendNotificationAsync(string message, List playerIds)
{
    try
    {
        // Sending notification code...
    }
    catch (HttpRequestException ex)
    {
        // Log or handle the error appropriately
        Console.WriteLine(ex.Message);
    }
}

This snippet demonstrates a simple way to catch exceptions that may occur when sending notifications. It’s crucial to implement robust error handling to avoid silent failures.

Performance & Best Practices

To ensure efficient use of OneSignal and optimal performance, consider the following best practices:

  • Batch Notifications: If you have multiple notifications to send, use OneSignal’s batch sending capabilities to reduce the number of API calls.
  • Efficient Targeting: Use segments effectively to target only those users who would find the notifications relevant, minimizing unnecessary notifications.
  • Rate Limits: Be aware of OneSignal's rate limits to avoid throttling your application. Monitor your usage to stay within acceptable limits.
  • Testing: Utilize the OneSignal dashboard to test notifications before sending them to all users. This can help catch formatting issues or incorrect targeting.

Real-World Scenario

In this scenario, we will create a simple ASP.NET Core Web API that allows users to register their devices for push notifications and send them updates about a fictional weather application.

[ApiController]
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
    private readonly OneSignalService _oneSignalService;

    public WeatherController(OneSignalService oneSignalService)
    {
        _oneSignalService = oneSignalService;
    }

    [HttpPost("register")] // Endpoint to register device
    public async Task RegisterDevice([FromBody] string playerId)
    {
        // Logic to save playerId to your database
        return Ok();
    }

    [HttpPost("notify")] // Endpoint to send notification
    public async Task SendWeatherUpdate([FromBody] string message)
    {
        // Logic to retrieve player IDs from your database
        var playerIds = new List { "playerId1", "playerId2" };
        await _oneSignalService.SendNotificationAsync(message, playerIds);
        return Ok();
    }
}

This controller provides two endpoints: one for registering devices and another for sending weather updates. The RegisterDevice method would typically involve saving the player ID to a database, while the SendWeatherUpdate method sends a notification to all registered devices.

Conclusion

  • OneSignal is a powerful tool for sending push notifications, enhancing user engagement in ASP.NET Core applications.
  • Proper configuration and error handling are crucial for successful integration.
  • Batching notifications and efficient targeting can improve performance and user experience.
  • Testing notifications through the OneSignal dashboard is essential before wide deployment.
  • Real-world applications can greatly benefit from using push notifications for timely updates.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Comprehensive Guide to QR Code Generation in ASP.NET Core Using QRCoder Library
Apr 23, 2026
Integrating Twilio SMS and Voice Calls in ASP.NET Core: A Comprehensive Guide
Apr 27, 2026
Integrating Twilio SMS in ASP.NET Core: SMS Sending, OTP Verification, and Voice Calls
Apr 27, 2026
Integrating CCAvenue Payment Gateway in ASP.NET Core Applications
Apr 24, 2026
Previous in ASP.NET Core
Integrating Twilio SMS and Voice Calls in ASP.NET Core: A Compreh…
Next in ASP.NET Core
AWS SNS SMS Integration in ASP.NET Core: Implementing Bulk SMS an…
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    Complete Guide to C++ Classes: Explained with Examples 4,212 views
  • 2
    Implementing an End-to-End CI/CD Pipeline for ASP.NET Core… 367 views
  • 3
    Create Database and CRUD operation 3,388 views
  • 4
    Mastering TypeScript Utility Types: Partial, Required, Rea… 675 views
  • 5
    Responsive Slick Slider 23,373 views
  • 6
    Integrating Azure Cognitive Search into ASP.NET Core Appli… 156 views
  • 7
    Integrating Anthropic Claude API in ASP.NET Core for AI Ch… 141 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26191 views
  • Exception Handling Asp.Net Core 20938 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20391 views
  • How to implement Paypal in Asp.Net Core 19753 views
  • Task Scheduler in Asp.Net core 17705 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor