适用于 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]
简化 ParameterNames
Use 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}.");
}
下面是 function.json 文件中的绑定数据:Here's binding data in the function.json file:
示例 function.json:Example function.json:
{
"type": "signalRTrigger",
"name": "invocation",
"hubName": "SignalRTest",
"category": "messages",
"event": "SendMessage",
"parameterNames": [
"message"
],
"direction": "in"
}
C# 脚本代码如下所示:Here's the C# Script code:
#r "Microsoft.Azure.WebJobs.Extensions.SignalRService"
using System;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Microsoft.Extensions.Logging;
public static void Run(InvocationContext invocation, string message, ILogger logger)
{
logger.LogInformation($"Receive {message} from {invocationContext.ConnectionId}.");
}
下面是 function.json 文件中的绑定数据:Here's binding data in the function.json file:
示例 function.json:Example function.json:
{
"type": "signalRTrigger",
"name": "invocation",
"hubName": "SignalRTest",
"category": "messages",
"event": "SendMessage",
"parameterNames": [
"message"
],
"direction": "in"
}
JavaScript 代码如下所示:Here's the JavaScript code:
module.exports = function (context, invocation) {
context.log(`Receive ${context.bindingData.message} from ${invocation.ConnectionId}.`)
context.done();
};
配置Configuration
SignalRTriggerSignalRTrigger
下表解释了在 function.json 文件和 SignalRTrigger
特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the SignalRTrigger
attribute.
function.json 属性function.json property |
Attribute 属性Attribute property |
说明Description |
typetype |
不适用n/a |
必须设置为 SignalRTrigger 。Must be set to SignalRTrigger . |
directiondirection |
不适用n/a |
必须设置为 in 。Must be set to in . |
namename |
不适用n/a |
在函数代码中用于“触发器调用上下文”对象的变量名称。Variable name used in function code for trigger invocation context object. |
hubNamehubName |
HubNameHubName |
此值必须设置为要触发的函数的 SignalR 中心的名称。This value must be set to the name of the SignalR hub for the function to be triggered. |
categorycategory |
类别Category |
此值必须设置为要触发的函数的消息类别。This value must be set as the category of messages for the function to be triggered. 类别可以是下列值之一:The category can be one of the following values: - 连接:包括“已连接”和“已断开连接”的事件 connections: Including connected and disconnected events
- 消息:包含除连接类别中事件的所有其他事件messages: Including all other events except those in connections category
|
eventevent |
事件Event |
此值必须设置为要触发的函数的消息事件。This value must be set as the event of messages for the function to be triggered. 对于消息类别,事件是客户端发送的调用消息中的目标 。For messages category, event is the target in invocation message that clients send. 对于连接类别,只使用“已连接”和“已断开连接” 。For connections category, only connected and disconnected is used. |
parameterNamesparameterNames |
ParameterNamesParameterNames |
(可选)绑定到参数的名称列表。(Optional) A list of names that binds to the parameters. |
connectionStringSettingconnectionStringSetting |
ConnectionStringSettingConnectionStringSetting |
应用设置的名称,该设置包含 SignalR 服务连接字符串(默认为“AzureSignalRConnectionString”)The name of the app setting that contains the SignalR Service connection string (defaults to "AzureSignalRConnectionString") |
有效负载Payload
触发器输入类型声明为 InvocationContext
或自定义类型。The trigger input type is declared as either InvocationContext
or a custom type. 如果选择 InvocationContext
,会获得对请求内容的完全访问权限。If you choose InvocationContext
you get full access to the request content. 对于自定义类型,运行时会尝试分析 JSON 请求正文,以设置对象属性。For a custom type, the runtime tries to parse the JSON request body to set the object properties.
InvocationContextInvocationContext
InvocationContext 包含 SignalR 服务发送的消息中的所有内容。InvocationContext contains all the content in the message send from SignalR Service.
InvocationContext 中的属性Property in InvocationContext |
说明Description |
参数Arguments |
可用于消息类别。Available for messages category. 包含调用消息中的参数Contains arguments in invocation message |
错误Error |
可用于“已断开连接”事件。Available for disconnected event. 如果连接关闭时未发生错误,可以为空,否则会包含错误消息。It can be Empty if the connection closed with no error, or it contains the error messages. |
HubHub |
消息所属的中心的名称。The hub name which the message belongs to. |
CategoryCategory |
消息的类别。The category of the message. |
事件Event |
消息的事件。The event of the message. |
ConnectionIdConnectionId |
发送消息的客户端的连接 ID。The connection ID of the client which sends the message. |
UserIdUserId |
发送消息的客户端的用户标识。The user identity of the client which sends the message. |
头文件Headers |
请求的标头。The headers of the request. |
查询Query |
客户端连接到服务时的请求的查询。The query of the request when clients connect to the service. |
声明Claims |
客户端的声明。The claims of the client. |
使用 ParameterNames
Using ParameterNames
通过 SignalRTrigger
中的属性 ParameterNames
,可将调用消息的参数绑定到函数的参数。The property ParameterNames
in SignalRTrigger
allows you to bind arguments of invocation messages to the parameters of functions. 你定义的名称可在其他绑定中用作绑定表达式的一部分,或者用作代码中的参数。The name you defined can be used as part of binding expressions in other binding or as parameters in your code. 这为你提供了更方便的方法来访问 InvocationContext
的参数。That gives you a more convenient way to access arguments of InvocationContext
.
假设你有 JavaScript SignalR 客户端尝试使用两个参数 message1
、message2
调用 Azure Function 中的方法 broadcast
。Say you have a JavaScript SignalR client trying to invoke method broadcast
in Azure Function with two arguments message1
, message2
.
await connection.invoke("broadcast", message1, message2);
设置 parameterNames
后,你定义的名称将分别对应于客户端发送的参数。After you set parameterNames
, the name you defined will respectively correspond to the arguments sent on the client side.
[SignalRTrigger(parameterNames: new string[] {"arg1, arg2"})]
然后,arg1
将包含 message1
的内容,arg2
将包含 message2
的内容。Then, the arg1
will contain the content of message1
, and arg2
will contain the content of message2
.
对于参数绑定,顺序很重要。For the parameter binding, the order matters. 如果使用 ParameterNames
,则 ParameterNames
中的顺序与在客户端中调用参数的顺序相匹配。If you are using ParameterNames
, the order in ParameterNames
matches the order of the arguments you invoke in the client. 如果在 C# 中使用特性 [SignalRParameter]
,则 Azure Function 方法中的参数顺序与客户端中参数的顺序相匹配。If you are using attribute [SignalRParameter]
in C#, the order of arguments in Azure Function methods matches the order of arguments in clients.
ParameterNames
和特性 [SignalRParameter]
不能同时使用,否则将出现异常。ParameterNames
and attribute [SignalRParameter]
cannot be used at the same time, or you will get an exception.
SignalR 服务集成SignalR Service integration
当你使用 SignalR 服务触发器绑定时,SignalR 服务需要一个用于访问函数应用的 URL。SignalR Service needs a URL to access Function App when you're using SignalR Service trigger binding. 应在 SignalR 服务端的 上游设置 中配置 URL。The URL should be configured in Upstream Settings on the SignalR Service side.
使用 SignalR 服务触发器时,URL 可以十分简单,其格式可以设置为如下所示:When using SignalR Service trigger, the URL can be simple and formatted as shown below:
<Function_App_URL>/runtime/webhooks/signalr?code=<API_KEY>
Function_App_URL
可在函数应用的“概述”页上找到,API_KEY
由 Azure Function 生成。The Function_App_URL
can be found on Function App's Overview page and The API_KEY
is generated by Azure Function. 可以从函数应用的“应用密钥”边栏选项卡中获取 signalr_extension
的 API_KEY
。You can get the API_KEY
from signalr_extension
in the App keys blade of Function App.
如果要将多个函数应用与一个 SignalR 服务一起使用,上游还可以支持复杂的路由规则。If you want to use more than one Function App together with one SignalR Service, upstream can also support complex routing rules. 有关更多详细信息,请查看上游设置。Find more details at Upstream settings.
分步示例Step by step sample
可以按照 GitHub 中的示例,使用 SignalR 服务触发器绑定和上游功能在函数应用上部署聊天室:双向聊天室示例You can follow the sample in GitHub to deploy a chat room on Function App with SignalR Service trigger binding and upstream feature: Bidirectional chat room sample
后续步骤Next steps