You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebJob SDK集成NotificationHub推送通知问题及SDK3适配咨询

解决WebJobs SDK2 NotificationHub绑定空引用异常,以及SDK3实现方案

一、解决SDK2中的空引用异常

你遇到的NullReferenceException大概率是因为NotificationHub的配置未正确设置,导致绑定[NotificationHub]参数时无法找到有效的Hub实例。按照以下步骤排查修复:

  1. 检查配置文件(App.config/Web.config)
    确保在appSettings节点中添加了NotificationHub的连接字符串和Hub名称:

    <appSettings>
      <!-- 必须:WebJobs存储连接字符串 -->
      <add key="AzureWebJobsStorage" value="你的Azure存储账户连接字符串"/>
      <!-- 必须:NotificationHub的DefaultFullSharedAccessSignature连接字符串 -->
      <add key="AzureWebJobsNotificationHubsConnectionString" value="你的NotificationHub连接字符串"/>
      <!-- 必须:你的NotificationHub名称 -->
      <add key="AzureWebJobsNotificationHubName" value="你的Hub名称"/>
    </appSettings>
    

    如果没有这些配置,config.UseNotificationHubs()无法初始化Hub客户端,绑定参数时就会抛出空引用异常。

  2. 显式指定Hub名称(可选)
    如果你的配置中没有全局设置Hub名称,也可以在[NotificationHub]属性中直接指定:

    public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log, [NotificationHub(HubName = "你的Hub名称")] out Notification notification)
    
  3. 验证连接字符串权限
    确保你使用的是NotificationHub的DefaultFullSharedAccessSignature连接字符串,而不是只读权限的,否则发送通知时会出现权限问题。

二、使用WebJobs SDK3实现NotificationHub推送

虽然Microsoft.Azure.Webjobs.Extensions.NotificationHub扩展暂时不兼容SDK3,但我们可以直接使用官方的Microsoft.Azure.NotificationHubs SDK,结合SDK3的依赖注入功能来实现推送,步骤如下:

1. 安装必要的NuGet包

Install-Package Microsoft.Azure.WebJobs
Install-Package Microsoft.Azure.WebJobs.Extensions.Storage
Install-Package Microsoft.Azure.NotificationHubs
Install-Package Microsoft.Extensions.Configuration.Json

2. 配置Program.cs(SDK3的Host初始化)

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Azure.NotificationHubs;

namespace WJNotificationHubSDK3
{
    class Program
    {
        static void Main()
        {
            var host = new HostBuilder()
                .ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices(); // 启用存储核心服务
                    b.AddAzureStorageQueues(); // 启用队列触发器
                })
                .ConfigureServices(services =>
                {
                    // 注册NotificationHubClient为单例服务
                    services.AddSingleton(sp =>
                    {
                        var config = sp.GetRequiredService<IConfiguration>();
                        var connectionString = config["AzureWebJobsNotificationHubsConnectionString"];
                        var hubName = config["AzureWebJobsNotificationHubName"];
                        return NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);
                    });
                })
                .Build();

            using (host)
            {
                host.Run();
            }
        }
    }
}

3. 编写Functions.cs(注入Hub客户端并发送通知)

using Microsoft.Azure.NotificationHubs;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace WJNotificationHubSDK3
{
    public class Functions
    {
        private readonly NotificationHubClient _notificationHubClient;

        // 通过构造函数注入NotificationHubClient
        public Functions(NotificationHubClient notificationHubClient)
        {
            _notificationHubClient = notificationHubClient;
        }

        [FunctionName("ProcessQueueMessage")]
        public async Task ProcessQueueMessage([QueueTrigger("queue")] string message, ILogger log)
        {
            log.LogInformation($"Received queue message: {message}");
            
            // 构造GCM payload
            var gcmPayload = message.ToGcmPayload();
            var notification = new GcmNotification(gcmPayload);
            
            // 发送通知(异步调用)
            await _notificationHubClient.SendNotificationAsync(notification);
            log.LogInformation("Notification sent successfully");
        }
    }

    public static class PlatformNotificationsExtensions
    {
        public static string ToGcmPayload(this string message)
        {
            var gcmPayloadModel = new
            {
                data = new
                {
                    message = message
                }
            };
            return JsonConvert.SerializeObject(gcmPayloadModel);
        }
    }
}

4. 配置appsettings.json

在项目根目录添加appsettings.json文件,并设置以下配置:

{
  "AzureWebJobsStorage": "你的Azure存储账户连接字符串",
  "AzureWebJobsNotificationHubsConnectionString": "你的NotificationHub连接字符串",
  "AzureWebJobsNotificationHubName": "你的Hub名称"
}

注意:要将该文件的“复制到输出目录”设置为“如果较新则复制”。

这样就能在SDK3中顺利实现从WebJobs向NotificationHub推送通知的功能了。

内容的提问来源于stack exchange,提问作者ikko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:28:18