适用于 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 that 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 that 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. 这为你提供了更方便的方法来访问 InvocationContext
的参数。That gives you a more convenient way to access arguments of InvocationContext
.
假设你有 JavaScript SignalR 客户端尝试调用 Azure Function 中带有两个参数的方法 broadcast
。Say you have a JavaScript SignalR client trying to invoke method broadcast
in Azure Function with two arguments.
await connection.invoke("broadcast", message1, message2);
你可以通过参数来访问这两个参数,也可使用 ParameterNames
为它们分配参数类型。You can access these two arguments from parameter as well as assign type of parameter for them by using ParameterNames
.
对于参数绑定,顺序很重要。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 服务触发器绑定Send messages to SignalR Service trigger binding
Azure Function 为 SignalR 服务触发器绑定生成 URL,其格式如下:Azure Function generates a URL for SignalR Service trigger binding and it is formatted as following:
https://<APP_NAME>.chinacloudsites.cn/runtime/webhooks/signalr?code=<API_KEY>
API_KEY
由 Azure Function 生成。The API_KEY
is generated by Azure Function. 使用 SignalR 服务触发器绑定时,可以从 Azure 门户中获取 API_KEY
。You can get the API_KEY
from Azure portal as you're using SignalR Service trigger binding.
应在 SignalR 服务的“上游设置”的 UrlTemplate
中设置此 URL。You should set this URL in UrlTemplate
in the upstream settings of SignalR Service.
后续步骤Next steps