Уведомление в режиме реального времени при регистрации с помощью SignalR - PullRequest
0 голосов
/ 15 мая 2018

Я хочу отправлять уведомления в режиме реального времени в ASP.NET Boilerplate.Уведомление успешно сохраняется в таблице Abp.NotificationSubscription при подписке.Когда я публикую уведомление, оно сохраняется в таблице Abp.Notification , но оно не отображается пользователю в режиме реального времени.

Мой код на стороне сервера:

public async Task<RegisterOutput> Register(RegisterInput input)
{
    public async Task<RegisterOutput> Register(RegisterInput input)
    {
      var user = await _userRegistrationManager.RegisterAsync(
          input.Name,
          input.Surname,
          input.EmailAddress,
          input.UserName,
          input.Password,
          true
      );

      _notificationSubscriptionManager.SubscribeToAllAvailableNotifications(user.ToUserIdentifier());
      await _appNotifier.WelcomeToTheApplicationAsync(user);

      var notification = _userNotificationManager.GetUserNotifications(user.ToUserIdentifier());
      await _realTimeNotifier.SendNotificationsAsync(notification.ToArray());

      // ...
    }
}

_appNotifier реализует WelcomeToTheApplicationAsync(user):

public async Task WelcomeToTheApplicationAsync(User user)
{
    await _notificationPublisher.PublishAsync(
        AppNotificationName.WelcomeToTheApplication,
        new SendNotificationData("Naeem", "Hello I have sended this notification to you"),
        severity: NotificationSeverity.Success,
        userIds: new[] { user.ToUserIdentifier() }
    );
}

SendNotificationData наследуется от NotificationData:

public class SendNotificationData : NotificationData
{
    public string name { get; set; }
    public string message { get; set; }

    public SendNotificationData(string _name, string _message)
    {
        name = _name;
        message = _message;
    }
}

1 Ответ

0 голосов
/ 16 мая 2018

Я хочу отправить приветственное уведомление пользователю, когда он регистрируется, используя ссылку регистрации на странице входа.В проекте CloudbaseLine.Application ... у нас есть AccountAppService , который содержит код для регистрации пользователя и отправки ему уведомления после успешной регистрации, но проблема заключается в том, что уведомление отправляется сохраненным в Abp.NotificationSubscriptionTable и UserNotificationTable , но пользователь не может их получить.

public async Task<RegisterOutput> Register(RegisterInput input)
{
    var user = await _userRegistrationManager.RegisterAsync(
        input.Name,
        input.Surname,
        input.EmailAddress,
        input.UserName,
        input.Password,
        true
    );

    _notificationSubscriptionManager.SubscribeToAllAvailableNotifications(user.ToUserIdentifier());
    await _appNotifier.WelcomeToTheApplicationAsync(user);

    var notification = _userNotificationManager.GetUserNotifications(user.ToUserIdentifier());
    await _realTimeNotifier.SendNotificationsAsync(notification.ToArray());

    // ...
}
public async Task WelcomeToTheApplicationAsync(User user)
{
    await _notificationPublisher.PublishAsync(
        AppNotificationName.WelcomeToTheApplication,
        new SendNotificationData("Naeem", "Hello I have sended this notification to you"),
        severity: NotificationSeverity.Success,
        userIds: new[] { user.ToUserIdentifier() }
    );
}

Пользователь не подключен к концентратору SignalR в RegisterМетод.

Один из способов справиться с этим - поставить фоновое задание в очередь :

await _backgroundJobManager.EnqueueAsync<WelcomeNotificationJob, UserIdentifier>(
    user.ToUserIdentifier(),
    delay: TimeSpan.FromSeconds(5)
);
public class WelcomeNotificationJob : BackgroundJob<UserIdentifier>, ITransientDependency
{
    private readonly IRealTimeNotifier _realTimeNotifier;
    private readonly IUserNotificationManager _userNotificationManager;

    public WelcomeNotificationJob(
        IRealTimeNotifier realTimeNotifier,
        IUserNotificationManager userNotificationManager)
    {
        _realTimeNotifier = realTimeNotifier;
        _userNotificationManager = userNotificationManager;
    }

    [UnitOfWork]
    public override void Execute(UserIdentifier args)
    {
        var notifications = _userNotificationManager.GetUserNotifications(args);
        AsyncHelper.RunSync(() => _realTimeNotifier.SendNotificationsAsync(notifications.ToArray()));
    }
}

Не забудьте зарегистрировать средства форматирования данных для пользовательских типов данных уведомлений на стороне клиента:

abp.notifications.messageFormatters['CloudBaseLine.Notification.SendNotificationData'] = function (userNotification) {
    return userNotification.notification.data.message;
}
...