Certainly! Setting up web push notifications using Azure Notification Hubs and integrating it with a .NET Core backend can be a bit complex, but I'll guide you through the process step by step.
Prerequisites
- Azure Subscription: Ensure you have an Azure subscription.
- Notification Hub: Create a Notification Hub in your Azure portal.
- VAPID Keys: Generate VAPID keys for Web Push. You can use tools like web-push-codelab to generate these keys.
Steps to Implement Web Push Notifications
Step 1: Install Azure Notification Hubs SDK
First, you need to install the Azure Notification Hubs SDK for .NET:
dotnet add package Microsoft.Azure.NotificationHubs
Step 2: Backend Setup
Here's a simple example of how to set up your .NET Core backend to handle browser installations and send notifications.
1. Create a Model for Registration
Create a model to represent the registration details:
public class Registration
{
public string Endpoint { get; set; }
public string P256dh { get; set; }
public string Auth { get; set; }
}
2. Create a Controller
Create an API controller to handle registration and sending notifications:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.NotificationHubs;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class NotificationsController : ControllerBase
{
private readonly NotificationHubClient _hub;
public NotificationsController()
{
string connectionString = "<Your_Notification_Hub_Connection_String>";
string hubName = "<Your_Notification_Hub_Name>";
_hub = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] Registration registration)
{
var installation = new Installation
{
InstallationId = Guid.NewGuid().ToString(),
Platform = NotificationPlatform.Web,
PushChannel = registration.Endpoint,
Tags = new List<string> { "browser" },
Templates = new Dictionary<string, InstallationTemplate>
{
["genericMessage"] = new InstallationTemplate
{
Body = "{ \"notification\": { \"title\": \"$(title)\", \"body\": \"$(message)\" } }"
}
}
};
installation.WebPushHeaders["p256dh"] = registration.P256dh;
installation.WebPushHeaders["auth"] = registration.Auth;
await _hub.CreateOrUpdateInstallationAsync(installation);
return Ok();
}
[HttpPost("send")]
public async Task<IActionResult> Send([FromBody] NotificationMessage message)
{
var notification = new Dictionary<string, string>
{
["title"] = message.Title,
["message"] = message.Body
};
await _hub.SendTemplateNotificationAsync(notification, "browser");
return Ok();
}
}
public class NotificationMessage
{
public string Title { get; set; }
public string Body { get; set; }
}
Step 3: Frontend Setup
In your frontend, you need to handle the service worker registration and the subscription process.
1. Service Worker
Create a service worker file (sw.js
):
self.addEventListener('push', function(event) {
var data = event.data.json();
self.registration.showNotification(data.notification.title, {
body: data.notification.body,
icon: '/path/to/icon.png'
});
});
2. Register Service Worker and Subscribe
In your main JavaScript file:
const vapidPublicKey = '<Your_VAPID_Public_Key>';
navigator.serviceWorker.register('/sw.js')
.then(function(registration) {
return registration.pushManager.getSubscription()
.then(async function(subscription) {
if (subscription) {
return subscription;
}
const response = await fetch('/api/notifications/publicKey');
const vapidPublicKey = await response.text();
const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
return registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: convertedVapidKey
});
});
}).then(function(subscription) {
fetch('/api/notifications/register', {
method: 'POST',
body: JSON.stringify({
endpoint: subscription.endpoint,
p256dh: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))),
auth: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth'))))
}),
headers: {
'Content-Type': 'application/json'
}
});
});
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
Summary
- Backend:
- Set up API endpoints for registration and sending notifications.
- Use the Azure Notification Hubs SDK to handle installations and notifications.
- Frontend:
- Register a service worker.
- Subscribe to push notifications and send the subscription details to your backend.
By following these steps and combining the backend and frontend code, you should be able to set up web push notifications using Azure Notification Hubs in a .NET Core application.
If you have any specific questions or need further assistance, feel free to ask!