Azure Functions 的 SignalR 服务触发器绑定SignalR Service trigger binding for Azure Functions

使用 SignalR 触发器绑定来响应从 Azure SignalR 服务发送的消息。Use the SignalR trigger binding to respond to messages sent from Azure SignalR Service. 触发函数时,传递给函数的消息分析为 json 对象。When function is triggered, messages passed to the function is parsed as a json object.

有关设置和配置详细信息,请参阅概述For information on setup and configuration details, see the overview.

示例Example

下面的示例演示一个函数,该函数使用触发器绑定来接收消息并记录该消息。The following example shows a function that receives a message using the trigger binding and log the message.

适用于 C# 的 SignalR 服务触发器绑定具有两种编程模型。SignalR Service trigger binding for C# has two programming models. 基于类的模型和传统模型。Class based model and traditional model. 基于类的模型可提供一致的 SignalR 服务器端编程体验。Class based model can provide a consistent SignalR server-side programming experience. 传统模型提供更大的灵活性,并与其他函数绑定类似。And traditional model provides more flexibility and similar with other function bindings.

使用基于类的模型With Class based model

有关详细信息,请参阅基于类的模型See Class based model for details.

public class SignalRTestHub : ServerlessHub
{
    [FunctionName("SignalRTest")]
    public async Task SendMessage([SignalRTrigger]InvocationContext invocationContext, string message, ILogger logger)
    {
        logger.LogInformation($"Receive {message} from {invocationContext.ConnectionId}.");
    }
}

对于传统模型With Traditional model

传统模型遵守使用 C# 开发的 Azure Function 的约定。Traditional model obeys the convention of Azure Function developed by C#. 如果不熟悉该约定,可通过文档了解和学习。If you're not familiar with it, you can learn from documents.

[FunctionName("SignalRTest")]
public static async Task Run([SignalRTrigger("SignalRTest", "messages", "SendMessage", parameterNames: new string[] {"message"})]InvocationContext invocationContext, string message, ILogger logger)
{
    logger.LogInformation($"Receive {message} from {invocationContext.ConnectionId}.");
}

使用特性 [SignalRParameter] 简化 ParameterNamesUse attribute [SignalRParameter] to simplify ParameterNames

由于使用 ParameterNames 有点麻烦,可使用 SignalRParameter 来实现同一目的。As it's bit cumbersome to use ParameterNames, SignalRParameter is provided to achieve the same purpose.

[FunctionName("SignalRTest")]
public static async Task Run([SignalRTrigger("SignalRTest", "messages", "SendMessage")]InvocationContext invocationContext, [SignalRParameter]string message, ILogger logger)
{
    logger.LogInformation($"Receive {message} from {invocationContext.ConnectionId}.");
}