最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

.net - Push notifications not displaying - Stack Overflow

programmeradmin1浏览0评论

I had to create a push notifications proof of concept with Angular + WebPush on a .Net BE.

Yesterday everything was working fine, while today something has changed and no notification is shown in the low right corner. I've tried to change network and the problem was still there.

  • No error is displayed
  • Every request returns 200

My Angular FE code uses swPush.requestSubscription and looks like this:

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './appponent.html',
  styleUrl: './appponent.scss'
})
export class AppComponent implements OnDestroy {

  baseUrl: string = // LOCALHOST + API PORT;

  headers = new Object(new HttpHeaders({
    "Authorization": //VALID TOKEN
  }));

  readonly VAPID_PUBLIC_KEY = //VALID PUBLIC KEY;


  constructor(private swPush: SwPush, private http: HttpClient) { }

  subscribeToNotifications() {
    
    this.swPush.requestSubscription({
      serverPublicKey: this.VAPID_PUBLIC_KEY
    })
      .then(sub => {

        this.saveSubscription(sub);

      })
      .catch((err) => {

        this.unsubscribeAllSubscriptions();

      });

  }



saveSubscription(sub: PushSubscription) {

    this.http.post(`${this.baseUrl}/PushNotification/Subscribe`, sub, this.headers).subscribe({
      next: () => {},
      error: (err) => {}
    })

  }

  testSubscription() {

    this.http.get(`${this.baseUrl}/PushNotification/Test?title=beautiful title&body=amazing body`, this.headers).subscribe({
      next: () => {},
      error: (err) => {}
    })

  }

  unsubscribeBESubscription() {

    this.http.get(`${this.baseUrl}/PushNotification/Unsubscribe`, this.headers).subscribe({
      next: () => {},
      error: (err) => {}
    })

  }

  unsubscribeAllSubscriptions() {
    this.swPush.unsubscribe();
    this.unsubscribeBESubscription();
  }

  ngOnDestroy(): void {
    this.unsubscribeAllSubscriptions();
  }

}

Meanwhile my BE code looks like this:

namespace TestTest.API.Controllers
{
    [ApiController]
    [Route("/[controller]/[action]")]
    public class PushNotificationController : ControllerBase
    {

        PushNotificationService _pushNotificationService;
        public static PushSubscription? _subscription;

        public PushNotificationController(PushNotificationService pushNotificationService)
        {
            _pushNotificationService = pushNotificationService;
        }

        
        [HttpPost]
        public IActionResult Subscribe([FromBody] PushSubscriptionModel subscription)
        {
            if (_subscription == null)
            {
                _subscription = new PushSubscription(subscription.Endpoint, subscription.Keys["p256dh"], subscription.Keys["auth"]);
                _pushNotificationService.SendNotification(_subscription, "User", "User subscribed");

            }

            return Ok();

        }

        [HttpGet]
        public IActionResult Unsubscribe()
        {
            if (_subscription != null)
            {
                _subscription = null;
            }

            return Ok();
        }

        [HttpGet]
        public IActionResult Test(string title, string body)
        {

            if (_subscription != null)
            {
                _pushNotificationService.SendNotification(_subscription, title, body);

            }

            return Ok();

        }

    }

}

This is the service code.

namespace TestTest.API.Services
{
    public class PushNotificationService
    {
        private readonly string _publicKey = //VALID PUBLIC KEY (same PK on FE);
        private readonly string _privateKey = //VALID PRIVATE KEY;
        private readonly VapidDetails _vapidDetails;

        public PushNotificationService()
        {
            _vapidDetails = new VapidDetails("mailto:[email protected]", _publicKey, _privateKey);
        }

        public void SendNotification(PushSubscription pushSubscription, string title, string body)
        {
           
            var webPushClient = new WebPushClient();
            var payload = $"{{ \"notification\": {{\"title\": \"{title}\", \"body\": \"{body}\"}} }}";

            try
            {
                webPushClient.SendNotification(pushSubscription, payload, _vapidDetails);
            }
            catch (WebPushException ex)
            {
                // ERROR MANAGEMENT
            }
        }
    }

}

What am I missing?

发布评论

评论列表(0)

  1. 暂无评论