如何在异步Azure函数中使用Azure通知中心?

时间:2017-12-16 17:45:21

标签: c# azure azure-functions azure-notificationhub

我尝试创建一个使用Azure通知中心的预编译Azure功能,但我在运行时遇到了一些困难。

我的问题概述如下。

我的步骤: 1.在Visual Studio中开始本地开发Azure功能。 2.创建使用NotificationHub属性的异步函数。例如,这是我的简化版本:

[FunctionName("MyFunction")]
    public static async Task Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, 
                                 [NotificationHub]IAsyncCollector<Notification> notification,
                                 TraceWriter log)
    {                                    
        using (var httpClient = new HttpClient())
        {
            try
            {
                // Make several async calls, and create a Windows TileNotification here...
                    await notification.AddAsync(new WindowsNotification(tileContent.GetContent()));
                }                    
            }                
            catch (Exception ex)
            {
                // log failure, etc.
            }
        }
    }

尝试在本地运行时收到以下错误消息:

Microsoft.Azure.WebJobs.Host:错误索引方法&#39; MyFunction.Run&#39;。

Microsoft.Azure.WebJobs.Host:无法绑定参数&#39;通知&#39;输入IAsyncCollector`1。确保绑定支持参数Type。如果您正在使用绑定扩展程序(例如ServiceBus, 计时器等)确保您已在启动代码中调用扩展名的注册方法(例如config.UseServiceBus(),config.UseTimers()等)。

该文档有几个使用out参数的同步示例,但没有异步示例,我不太确定错误消息试图告诉我的内容。我的NotificationHub属性是否需要其他配置?我是否需要一个functions.json文件,即使我正在使用预编译属性?

1 个答案:

答案 0 :(得分:0)

As Roman Kiss mentioned that we need to configure notification attribute properties such as ConnectionStringSetting, HubName. For precompiled C# functions, use the NotificationHub attribute, which is defined in NuGet package Microsoft.Azure.WebJobs.Extensions.NotificationHubs.

To configure the binding, add the NotificationHubs namespace connection string as an app setting or environment variable using the setting name AzureWebJobsNotificationHubsConnectionString

public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, [NotificationHub(HubName = "tomnotification", ConnectionStringSetting = "AzureWebJobsNotificationHubsConnectionString")]IAsyncCollector<Notification> notification, TraceWriter log)
    {
        //add you logic
    }

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "storage connection string",
    "AzureWebJobsDashboard": "storage connection string",
    "AzureWebJobsNotificationHubsConnectionString": "notifiaction hub connection string"
  }
}

Test result:

enter image description here