ASP.NET Boilerplate 通知系统(Notification System)实战指南:从订阅、发布到实时推送与多通道通知

原创2026-09-22 15:54:492,281 阅读
文章标签:后端Web框架依赖注入认证鉴权企业应用

ASP.NET Boilerplate 通知系统(Notification System)实战指南:从订阅、发布到实时推送与多通道通知

ASP.NET Boilerplate(ABP)提供了一套基于发布/订阅(Pub/Sub)的实时通知系统,用于在系统中发生特定事件时向用户推送信息。本文以官方文档 Notification-System.md 为主线,结合仓库 src/Abp/Notifications 下的源码实现,完整讲解通知的发送模型、订阅管理、发布 API、通知数据与严重级别、实时通知器(SignalR / Email / SMS 多通道)、客户端接收处理以及通知存储与定义,帮助你从零构建一套可订阅、可推送、可持久化的通知体系。

1. 通知系统核心概念

1.1 两种发送模型

ABP 的通知系统支持两种向用户发送通知的方式:

  • 订阅-发布模型(Pub/Sub):用户先订阅某一通知类型,之后每当该类型被发布时,通知会被投递给所有已订阅的用户。适用于"所有关注该事件的用户都应收到"的场景。
  • 定向直发模型(Direct):直接向指定用户发送通知,接收者无需订阅。适用于"只告诉某人"的场景。

注意:如果通过 userIds 向特定用户发布通知,这些用户不需要事先订阅该通知(文档明确说明,源码 NotificationPublisher.cs 的注释也印证了这一点)。

1.2 两种通知类型

  • 通用通知(General notifications):任意类型的通知,与具体实体无关。例如"当有人向我发送好友请求时通知我"。
  • 实体通知(Entity notifications):与某个具体实体关联的通知。例如"当有人评论这张照片时通知我"——它关联到某一特定照片实体,用户可以只订阅部分实体的通知。

1.3 通知数据(Notification Data)

通知一般携带通知数据。例如"好友请求"通知可能包含两个数据属性:发送者用户名和请求附言。通知数据类型与通知类型强耦合——不同类型通知对应不同数据类型。

通知数据是可选的,有些通知无需携带数据。框架内置了两个开箱即用的数据类:

  • MessageNotificationData:携带简单文本消息,源码见 MessageNotificationData.cs,仅含一个 Message 属性。
  • LocalizableMessageNotificationData:携带可本地化、可带参数的通知消息,源码见 LocalizableMessageNotificationData.cs,内部持有 LocalizableString Message,并支持通过字典存放参数。

所有自定义通知数据类都继承自 NotificationData,该基类内置了一个 Dictionary<string, object> Properties 字典和索引器 this[string key],因此任何通知数据都可以附带任意数量的自定义键值属性;其 Type 属性默认返回类的全名(含命名空间),客户端可据此判断数据类型(后文 JSON 示例中的 type 字段即来源于此)。

1.4 通知严重级别(Notification Severity)

严重级别定义在 NotificationSeverity 枚举中,共 5 级,默认值为 Info。源码见 NotificationSeverity.cs:

枚举值 数值 含义
Info 0 普通信息(默认)
Success 1 成功
Warn 2 警告
Error 3 错误
Fatal 4 致命

该枚举在发布通知时作为 severity 参数传入,并随通知 JSON 下发到客户端(severity: 0 即 Info)。

2. 订阅通知(INotificationSubscriptionManager)

INotificationSubscriptionManager 提供订阅管理的完整 API,其全部方法签名见 INotificationSubscriptionManager.cs。核心能力包括:

  • SubscribeAsync(user, notificationName, entityIdentifier, targetNotifiers):订阅指定通知;可传实体标识订阅实体通知;还可通过 targetNotifiers 指定只接收特定通知器(Notifier)的通知,值须为通知器的完整类型名(可用 new EmailRealTimeNotifier().GetType().FullName 获取),多个值用逗号分隔。
  • UnsubscribeAsync / Unsubscribe:取消订阅。
  • IsSubscribedAsync / IsSubscribed:判断是否已订阅。
  • GetSubscriptionsAsync / GetSubscriptions:查询某通知(或某实体通知)的全部订阅者。
  • GetSubscribedNotificationsAsync:查询某用户订阅了哪些通知。
  • SubscribeToAllAvailableNotificationsAsync:一键订阅该用户可用的所有通用通知(不含实体通知)。

从实现看(NotificationSubscriptionManager.cs),SubscribeAsync 内部先检查是否已订阅,已订阅则直接返回(幂等操作),再通过 INotificationStore.InsertSubscriptionAsync 写入订阅记录。

使用示例(摘自官方文档):

public class MyService : ITransientDependency
{
    private readonly INotificationSubscriptionManager _notificationSubscriptionManager;

    public MyService(INotificationSubscriptionManager notificationSubscriptionManager)
    {
        _notificationSubscriptionManager = notificationSubscriptionManager;
    }

    //订阅一个通用通知
    public async Task Subscribe_SentFriendshipRequest(int? tenantId, long userId)
    {
        await _notificationSubscriptionManager.SubscribeAsync(
            new UserIdentifier(tenantId, userId), "SentFriendshipRequest");
    }

    //订阅一个实体通知(针对某张具体照片)
    public async Task Subscribe_CommentPhoto(int? tenantId, long userId, Guid photoId)
    {
        await _notificationSubscriptionManager.SubscribeAsync(
            new UserIdentifier(tenantId, userId), "CommentPhoto",
            new EntityIdentifier(typeof(Photo), photoId));
    }
}

其中 INotificationSubscriptionManager 通过属性注入(参考 Dependency-Injection.md)。注意:每个通知类型必须有唯一名称(如示例中的 SentFriendshipRequest、CommentPhoto)。

3. 发布通知(INotificationPublisher)

INotificationPublisher 用于发布通知,其 PublishAsync 完整签名见 INotificationPublisher.cs:

Task PublishAsync(
    string notificationName,
    NotificationData data = null,
    EntityIdentifier entityIdentifier = null,
    NotificationSeverity severity = NotificationSeverity.Info,
    UserIdentifier[] userIds = null,
    UserIdentifier[] excludedUserIds = null,
    int?[] tenantIds = null,
    Type[] targetNotifiers = null);

各参数含义:

  • notificationName:通知的唯一名称(必填)。
  • data:通知数据(可选)。
  • entityIdentifier:实体标识,用于发布实体通知(可选)。
  • severity:严重级别,默认 Info。
  • userIds:目标用户列表。一旦设置即定向直发,不检查订阅;为空则投递给订阅者。
  • excludedUserIds:在向订阅者广播时排除的特定用户(通常与 userIds 互斥使用)。
  • tenantIds:目标租户(向指定租户的订阅者广播)。不应与 userIds 同时设置;传 NotificationPublisher.AllTenants 表示所有租户(仅适用于单数据库多租户方案);为 null 时默认取当前会话租户 IAbpSession.TenantId。
  • targetNotifiers:指定由哪些实时通知器处理该通知(必须在配置中注册过,见第 5 节)。

3.1 发布示例

public class MyService : ITransientDependency
{
    private readonly INotificationPublisher _notificationPublisher;

    public MyService(INotificationPublisher notificationPublisher)
    {
        _notificationPublisher = notificationPublisher;
    }

    //向指定用户发送通用通知
    public async Task Publish_SentFriendshipRequest(string senderUserName, string friendshipMessage, UserIdentifier targetUserId)
    {
        await _notificationPublisher.PublishAsync(
            "SentFriendshipRequest",
            new SentFriendshipRequestNotificationData(senderUserName, friendshipMessage),
            userIds: new[] { targetUserId });
    }

    //向指定用户发送实体通知
    public async Task Publish_CommentPhoto(string commenterUserName, string comment, Guid photoId, UserIdentifier photoOwnerUserId)
    {
        await _notificationPublisher.PublishAsync(
            "CommentPhoto",
            new CommentPhotoNotificationData(commenterUserName, comment),
            new EntityIdentifier(typeof(Photo), photoId),
            userIds: new[] { photoOwnerUserId });
    }

    //向当前租户所有订阅者广播,使用内置可本地化数据类 + Warn 级别
    public async Task Publish_LowDisk(int remainingDiskInMb)
    {
        //示例文案:English -> "Attention! Only {remainingDiskInMb} MBs left on the disk!"
        var data = new LocalizableMessageNotificationData(
            new LocalizableString("LowDiskWarningMessage", "MyLocalizationSourceName"));
        data["remainingDiskInMb"] = remainingDiskInMb;

        await _notificationPublisher.PublishAsync(
            "System.LowDisk", data, severity: NotificationSeverity.Warn);
    }
}

3.2 自定义通知数据类

SentFriendshipRequestNotificationData 应继承 NotificationData:

[Serializable]
public class SentFriendshipRequestNotificationData : NotificationData
{
    public string SenderUserName { get; set; }

    public string FriendshipMessage { get; set; }

    public SentFriendshipRequestNotificationData(string senderUserName, string friendshipMessage)
    {
        SenderUserName = senderUserName;
        FriendshipMessage = friendshipMessage;
    }
}

提示:默认采用 JSON 序列化,通知数据类不必须标记 [Serializable],但文档建议标记它——因为将来可能需要在应用间迁移通知并改用二进制序列化。

第三个示例展示了不定义专用数据类的做法:直接使用内置 LocalizableMessageNotificationData,通过字典式属性 data<a href="https://link.gitcode.com/i/99828af4592f61928e6a8f8ecc4fdbea" target="_blank">"remainingDiskInMb"] 存放参数,并将通知发布为 Warn 级别。本地化文案可引用这些参数(如 "Attention! Only {remainingDiskInMb} MBs left on the disk!"),本地化机制参见 [Localization.md,客户端侧的替换方式见第 6 节。

3.3 发布背后的分发逻辑(源码剖析)

从 NotificationPublisher.cs 的实现可以看到完整的发布链路:

  1. 校验 notificationName 非空、tenantIds 与 userIds 不能同时设置;若两者都为空则默认取当前会话租户。
  2. 构造 NotificationInfo(含名称、实体信息、严重级别、用户/排除用户/租户列表、数据 JSON 与数据类型名),并通过 SetTargetNotifiers 校验 targetNotifiers 均已注册后写入。
  3. 调用 INotificationStore.InsertNotificationAsync 持久化通知,并 SaveChanges 取得通知 Id。
  4. 分发策略优化:当 userIds 数量 <= 5(常量 MaxUserCountToDirectlyDistributeANotification = 5)时,直接调用 INotificationDistributer.DistributeAsync 同步分发;否则投递一个 NotificationDistributionJob 后台任务(参见 Background-Jobs-And-Workers.md)异步分发。

这意味着发布通知不保证立即送达——实时通知可能因后台任务而存在微小延迟。

4. 用户通知管理(IUserNotificationManager)

IUserNotificationManager 用于管理用户的通知记录,提供获取、更新(标记已读)、删除用户通知的方法,适合用来实现"我的通知列表"页面。它与实时推送互补:实时通道负责即时触达,而该管理器负责历史记录与状态管理(UserNotificationState 枚举:0=Unread 未读,1=Read 已读)。

5. 实时通知(IRealTimeNotifier)与多通道通知器

实时推送通过 IRealTimeNotifier 完成,该接口定义见 IRealTimeNotifier.cs,包含两个成员:

  • Task SendNotificationsAsync(UserNotification[] userNotifications):向指定用户投递实时通知,用户不在线时应忽略。
  • bool UseOnlyIfRequestedAsTarget { get; }:核心开关——为 true 时,该通知器仅在被显式指定为目标时才使用;为 false 时,它默认处理所有通知。

官方文档列举了可实现的实时通道:SignalR、Email、SMS。其中 SignalR 以独立包形式实现(Abp.AspNetCore.SignalR,见 src/Abp.AspNetCore.SignalR),SignalR-Integration.md 有专门说明,官方启动模板已内置。

5.1 实现自己的多通道通知器

ABP 支持注册多个 IRealTimeNotifier 并行工作。例如实现邮件与短信两个通道:

public class EmailRealTimeNotifier : IRealTimeNotifier, ITransientDependency
{
    bool UseOnlyIfRequestedAsTarget => false; // 默认处理所有通知

    private readonly IEmailSender _emailSender;
    private readonly UserManager _userManager;

    public EmailRealTimeNotifier(IEmailSender emailSender, UserManager userManager)
    {
        _emailSender = emailSender;
        _userManager = userManager;
    }

    public async Task SendNotificationsAsync(UserNotification[] userNotifications)
    {
        foreach (var userNotification in userNotifications)
        {
            if (userNotification.Notification.Data is MessageNotificationData data)
            {
                var user = await _userManager.GetUserByIdAsync(userNotification.UserId);
                _emailSender.Send(
                    to: user.EmailAddress,
                    subject: "You have a new notification!",
                    body: data.Message,
                    isBodyHtml: true);
            }
        }
    }
}
public class SMSRealTimeNotifier : IRealTimeNotifier, ITransientDependency
{
    bool UseOnlyIfRequestedAsTarget => true; // 仅在显式指定时才使用

    private readonly IUserSMSSender _userSmsSender;

    public SMSRealTimeNotifier(IUserSMSSender userSmsSender)
    {
        _userSmsSender = userSmsSender;
    }

    public async Task SendNotificationsAsync(UserNotification[] userNotifications)
    {
        foreach (var userNotification in userNotifications)
        {
            if (userNotification.Notification.Data is MessageNotificationData data)
            {
                var user = await _userManager.GetUserByIdAsync(userNotification.UserId);
                _userSmsSender.Send(user, data.Message);
            }
        }
    }
}

注:原文的 SMSRealTimeNotifier 示例中使用了 _userManager,但构造器未注入,实际编写时应像 EmailRealTimeNotifier 一样注入 UserManager。

5.2 注册通知器

在模块的 PreInitialize 方法中注册(配置对象见 NotificationConfiguration.cs,其中 Notifiers 是一个 ITypeList<IRealTimeNotifier>):

Configuration.Notifications.Notifiers.Add<EmailRealTimeNotifier>();
Configuration.Notifications.Notifiers.Add<SMSRealTimeNotifier>();

5.3 发布时选择通知通道

默认情况下,UseOnlyIfRequestedAsTarget == false 的通知器(如 EmailRealTimeNotifier 和默认的 SignalRRealTimeNotifier)会处理所有通知;而 SMSRealTimeNotifier 因 UseOnlyIfRequestedAsTarget == true,必须通过 targetNotifiers 显式指定才会被使用:

// 发给所有订阅者,由 Email + SignalR(默认通知器)投递
public async Task Publish_NewUserCreatedNotification(long userId)
{
    var data = new LocalizableMessageNotificationData(
        new LocalizableString("NewUserCreated", "MyLocalizationSourceName"));

    await _notificationPublisher.PublishAsync("System.NewUserCreated", data);
}

// 只通过 SMS 投递
public async Task Publish_NewUserCreatedNotificationWithSms(long userId)
{
    var data = new LocalizableMessageNotificationData(
        new LocalizableString("NewUserCreated", "MyLocalizationSourceName"));

    await _notificationPublisher.PublishAsync(
        "System.NewUserCreated", data,
        targetNotifiers: new Type[] { typeof(SMSRealTimeNotifier) });
}

源码层面的校验:NotificationPublisher.SetTargetNotifiers(NotificationPublisher.cs)会检查 targetNotifiers 中每个通知器是否已加入 Configuration.Notifications.Notifiers,未注册会抛出异常。同理,第 2 节订阅时的 targetNotifiers 参数也会将通知限定为只接收指定通道,未被选中的通知器不会向该用户发送。

6. 客户端接收与展示(SignalR + JavaScript)

6.1 监听全局事件

当实时通知经 SignalR 到达时,ABP 会在客户端触发一个全局事件 abp.notifications.received,注册监听即可接收:

abp.event.on('abp.notifications.received', function (userNotification) {
    console.log(userNotification);
});

事件机制详见 Javascript-API/Event-Bus.md。

6.2 通知 JSON 结构解析

以 System.LowDisk 通知为例,客户端收到的 JSON 如下:

{
    "userId": 2,
    "state": 0,
    "notification": {
        "notificationName": "System.LowDisk",
        "data": {
            "message": {
                "sourceName": "MyLocalizationSourceName",
                "name": "LowDiskWarningMessage"
            },
            "type": "Abp.Notifications.LocalizableMessageNotificationData",
            "properties": {
                "remainingDiskInMb": "42"
            }
        },
        "entityType": null,
        "entityTypeName": null,
        "entityId": null,
        "severity": 0,
        "creationTime": "2016-02-09T17:03:32.13",
        "id": "0263d581-3d8a-476b-8e16-4f6a6f10a632"
    },
    "id": "4a546baf-bf17-4924-b993-32e420a8d468"
}

字段含义:

  • userId:当前用户 Id(客户端一般已知,可忽略)。
  • state:UserNotificationState 枚举值,0=Unread(未读),1=Read(已读)。
  • notification:通知详情。
    • notificationName:通知唯一名称(与发布时一致)。
    • data:通知数据。本例为 LocalizableMessageNotificationData。
      • message:可本地化消息信息,含 sourceName 与 name,可据此在 UI 上做本地化。
      • type:通知数据类型(含命名空间的完整类型名),处理数据前应据此判断类型。
      • properties:字典式自定义属性。
    • entityType / entityTypeName / entityId:实体通知时携带的实体信息,否则为 null。
    • severity:NotificationSeverity 枚举值,0=Info、1=Success、2=Warn、3=Error、4=Fatal。
    • creationTime:通知创建时间。
    • id:通知 Id。
  • id:用户通知 Id。

6.3 根据数据类型渲染通知

可以不止于打印日志——示例演示了如何取出并本地化通知内容:

abp.event.on('abp.notifications.received', function (userNotification) {
    if (userNotification.notification.data.type === 'Abp.Notifications.LocalizableMessageNotificationData') {
        var localizedText = abp.localization.localize(
            userNotification.notification.data.message.name,
            userNotification.notification.data.message.sourceName
        );

        $.each(userNotification.notification.data.properties, function (key, value) {
            localizedText = localizedText.replace('{' + key + '}', value);
        });

        alert('New localized notification: ' + localizedText);
    } else if (userNotification.notification.data.type === 'Abp.Notifications.MessageNotificationData') {
        alert('New simple notification: ' + userNotification.notification.data.message);
    }
});

处理流程:先判断 data.type——对可本地化数据,用 abp.localization.localize 取文案并逐一把 properties 中的参数替换进 {key} 占位符;对简单消息则直接读取 message。真实项目中不建议用 alert,可改用 Javascript-API/Notification.md 的 abp.notify API 呈现更美观的 UI 通知。

6.4 一行代码搞定 UI 通知

更简单、可扩展的做法:收到推送后直接调用内置方法渲染 UI 通知:

abp.event.on('abp.notifications.received', function (userNotification) {
    abp.notifications.showUiNotifyForUserNotification(userNotification);
});

showUiNotifyForUserNotification 对内置数据类(LocalizableMessageNotificationData 与 MessageNotificationData)开箱即用,效果如下(对应上文发布的 System.LowDisk 通知):

Warn 级别的 UI 通知效果示例(System.LowDisk 通知)

如果使用了自定义通知数据类,需要注册消息格式化器:

abp.notifications.messageFormatters['MyProject.MyNotificationDataType'] = function (userNotification) {
    return ...; // 格式化并返回消息
};

这样 showUiNotifyForUserNotification 即可为你的数据类型生成展示文本。若只需要格式化后的消息,可直接调用其内部使用的 abp.notifications.getFormattedMessageFromUserNotification(userNotification)。官方启动模板已包含"收到推送即显示 UI 通知"的代码。

7. 通知存储(INotificationStore)

通知系统依赖 INotificationStore 持久化通知与订阅。为了让系统正常工作,必须实现该接口——你可以自行实现,也可以直接使用 Module Zero(其已完整实现,见 Abp.Zero.Common 下的相关实现)。仓库还提供了 NullNotificationStore.cs 空实现供测试等场景使用。

存储层承载了订阅记录、通知记录与用户通知记录(NotificationSubscriptionInfo、NotificationInfo、UserNotificationInfo 等实体,见 src/Abp/Notifications),这也是第 3.3 节中"先持久化、再分发"流程的落点。

8. 通知定义(Notification Definitions)

并非必须预先定义通知才能使用——你可以直接用任意通知名发布。但定义通知能带来额外收益,例如枚举并审计应用中全部通知,进而为订阅页提供数据来源。

8.1 定义通知提供者

通过继承 NotificationProvider 定义通知(该类位于 NotificationProvider.cs):

public class MyAppNotificationProvider : NotificationProvider
{
    public override void SetNotifications(INotificationDefinitionContext context)
    {
        context.Manager.Add(
            new NotificationDefinition(
                "App.NewUserRegistered",
                displayName: new LocalizableString(
                    "NewUserRegisteredNotificationDefinition", "MyLocalizationSourceName"),
                permissionDependency: new SimplePermissionDependency(
                    "App.Pages.UserManagement")
            )
        );
    }
}
  • "App.NewUserRegistered":通知唯一名称(定义中必填)。
  • displayName:可本地化的显示名,可在订阅 UI 上展示。
  • permissionDependency:权限依赖——用户只有拥有 App.Pages.UserManagement 权限时才可见/可订阅该通知(权限体系见 Authorization.md)。

从 NotificationDefinition.cs 可以看到定义还支持更多可选参数:

  • entityType:关联实体类型(实体通知)。
  • description:可本地化描述。
  • featureDependency:功能依赖——租户启用对应功能(Feature)后才可用。
  • Attributes:任意自定义键值属性(须可序列化)。

8.2 注册通知提供者

在模块的 PreInitialize 中注册(配置对象 NotificationConfiguration.cs 中的 Providers 列表;PreInitialize 生命周期见 Module-System.md):

public class AbpZeroTemplateCoreModule : AbpModule
{
    public override void PreInitialize()
    {
        Configuration.Notifications.Providers.Add<MyAppNotificationProvider>();
    }

    //...
}

8.3 查询通知定义

最后,在应用代码中注入 INotificationDefinitionManager(见 INotificationDefinitionManager.cs)即可获取全部通知定义,进而实现一个"自动化的通知订阅页面",把已定义通知展示给用户勾选订阅。

9. 全流程串联与最佳实践

一条通知从产生到展示的完整链路:

  1. 定义(可选):在 NotificationProvider 中声明通知名称、显示名、权限/功能依赖,并在 PreInitialize 注册。
  2. 订阅:用户通过 INotificationSubscriptionManager 订阅通用或实体通知(可限定通知通道)。
  3. 发布:INotificationPublisher.PublishAsync 校验参数、构造 NotificationInfo、持久化;接收者 ≤ 5 时同步分发,否则投递后台任务异步分发。
  4. 存储与分发:INotificationStore 落库,INotificationDistributer 计算目标用户;IRealTimeNotifier(SignalR/Email/SMS 等)按 UseOnlyIfRequestedAsTarget 与 targetNotifiers 规则投递。
  5. 客户端接收:SignalR 到达后触发 abp.notifications.received 全局事件;按 data.type 格式化,用 showUiNotifyForUserNotification 一行代码渲染 UI 通知;历史记录与已读状态由 IUserNotificationManager 管理。

实践建议:

  • 为每个通知使用唯一、可读的名称(建议带命名空间风格前缀,如 System.LowDisk)。
  • 数据量小、接收者少(≤5 人)时发布是同步快速路径;面向大量订阅者的广播走后台任务,注意接受其微小延迟。
  • 自定义通知数据类建议标记 [Serializable],为将来跨应用二进制序列化迁移留有余地。
  • 多通道场景下,让"默认全量投递"的通知器(UseOnlyIfRequestedAsTarget = false)承担通用职责,把短信等昂贵通道设为 true 并按需指定 targetNotifiers,避免成本失控。
  • 需要持久化与订阅管理时,优先复用 Module Zero 的现成 INotificationStore 实现,而不是重复造轮子。

相关资源:通知系统的全部核心接口与实现位于 src/Abp/Notifications;SignalR 集成见 SignalR-Integration.md;客户端 UI 通知 API 见 Javascript-API/Notification.md;Module Zero 的通知存储与权限整合见 Zero/Overall.md。

登录后查看全文
aspnetboilerplate