Azure Functions 的 SignalR 服务输出绑定

使用 Azure SignalR 服务,通过 SignalR 输出绑定发送一条或多条消息。 可以将消息广播到:

  • 所有连接的客户端
  • 对特定用户进行身份验证的已连接客户端

输出绑定还允许管理组。

若要了解设置和配置详细信息,请参阅概述

示例

可使用以下 C# 模式之一来创建 C# 函数:

  • 进程内类库:编译的 C# 函数,该函数在与 Functions 运行时相同的进程中运行。
  • 独立工作进程类库:编译的 C# 函数,该函数在独立于运行时的工作进程中运行。 需要独立工作进程才能支持在 LTS 和非 LTS 版 .NET 和 .NET Framework 上运行的 C# 函数。
  • C# 脚本:主要用于在 Azure 门户中创建 C# 函数。

广播到所有客户端

以下示例演示使用输出绑定将一条消息发送给所有连接的客户端的函数。 newMessage 是要在每个客户端上调用的方法的名称。

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.IO;
using System.Linq;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;

namespace SampleApp
{
    /// <summary>
    /// The class is the same as SignalROutputBindingFunctions except the comments. Just keep the original one because the learn website refers to it.
    /// </summary>
    public static class SignalROutputBindingFunctions2
    {
        // <snippet_broadcast_to_all>
        [Function(nameof(BroadcastToAll))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction BroadcastToAll([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                // broadcast to all the connected clients without specifying any connection, user or group.
                Arguments = new[] { bodyReader.ReadToEnd() },
            };
        }
        // </snippet_broadcast_to_all>

        // <snippet_send_to_connection>
        [Function(nameof(SendToConnection))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToConnection([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                ConnectionId = "connectionToSend",
            };
        }
        // </snippet_send_to_connection>

        // <snippet_send_to_user>
        [Function(nameof(SendToUser))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToUser([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                UserId = "userToSend",
            };
        }
        // </snippet_send_to_user>

        // <snippet_send_to_group>
        [Function(nameof(SendToGroup))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                GroupName = "groupToSend"
            };
        }
        // </snippet_send_to_group>

        // <snippet_send_to_endpoint>
        [Function(nameof(SendToEndpoint))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToEndpoint(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req,
            [SignalREndpointsInput("chat", ConnectionStringSetting = "SignalRConnection")] SignalREndpoint[] endpoints)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                // Only send to primary endpoint if you have configured multiple SignalR Service instances.
                // The use of 'Endpoints' can be combined with other properties such as UserId, GroupName, ConnectionID.
                Endpoints = endpoints.Where(e => e.EndpointType == SignalREndpointType.Primary).ToArray()
            };
        }
        // </snippet_send_to_endpoint>

        // <snippet_remove_from_group>
        [Function(nameof(RemoveFromGroup))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRGroupAction RemoveFromGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            return new SignalRGroupAction(SignalRGroupActionType.Remove)
            {
                GroupName = "group1",
                UserId = "user1"
            };
        }
        // </snippet_remove_from_group>
    }
}

广播到所有客户端

下面是 function.json 文件中的绑定数据:

示例 function.json:

{
  "type": "signalR",
  "name": "signalRMessages",
  "hubName": "<hub_name>",
  "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
  "direction": "out"
}

JavaScript 代码如下所示:

module.exports = async function (context, req) {
    context.bindings.signalRMessages = [{
        "target": "newMessage",
        "arguments": [ req.body ]
    }];
};

完整的 PowerShell 示例处于待定状态。

下面是 Python 代码:

def main(req: func.HttpRequest, outMessage: func.Out[str]) -> func.HttpResponse:
    message = req.get_json()
    outMessage.set(json.dumps({
        'target': 'newMessage',
        'arguments': [ message ]
    }))

广播到所有客户端

@FunctionName("sendMessage")
@SignalROutput(name = "$return", hubName = "chat")
public SignalRMessage sendMessage(
        @HttpTrigger(
            name = "req",
            methods = { HttpMethod.POST },
            authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req) {

    SignalRMessage message = new SignalRMessage();
    message.target = "newMessage";
    message.arguments.add(req.getBody());
    return message;
}

发送给用户

可以设置 SignalR 消息的用户 ID,以便将消息只发送给已针对某个用户进行身份验证的连接 。

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.IO;
using System.Linq;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;

namespace SampleApp
{
    /// <summary>
    /// The class is the same as SignalROutputBindingFunctions except the comments. Just keep the original one because the learn website refers to it.
    /// </summary>
    public static class SignalROutputBindingFunctions2
    {
        // <snippet_broadcast_to_all>
        [Function(nameof(BroadcastToAll))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction BroadcastToAll([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                // broadcast to all the connected clients without specifying any connection, user or group.
                Arguments = new[] { bodyReader.ReadToEnd() },
            };
        }
        // </snippet_broadcast_to_all>

        // <snippet_send_to_connection>
        [Function(nameof(SendToConnection))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToConnection([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                ConnectionId = "connectionToSend",
            };
        }
        // </snippet_send_to_connection>

        // <snippet_send_to_user>
        [Function(nameof(SendToUser))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToUser([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                UserId = "userToSend",
            };
        }
        // </snippet_send_to_user>

        // <snippet_send_to_group>
        [Function(nameof(SendToGroup))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                GroupName = "groupToSend"
            };
        }
        // </snippet_send_to_group>

        // <snippet_send_to_endpoint>
        [Function(nameof(SendToEndpoint))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToEndpoint(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req,
            [SignalREndpointsInput("chat", ConnectionStringSetting = "SignalRConnection")] SignalREndpoint[] endpoints)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                // Only send to primary endpoint if you have configured multiple SignalR Service instances.
                // The use of 'Endpoints' can be combined with other properties such as UserId, GroupName, ConnectionID.
                Endpoints = endpoints.Where(e => e.EndpointType == SignalREndpointType.Primary).ToArray()
            };
        }
        // </snippet_send_to_endpoint>

        // <snippet_remove_from_group>
        [Function(nameof(RemoveFromGroup))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRGroupAction RemoveFromGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            return new SignalRGroupAction(SignalRGroupActionType.Remove)
            {
                GroupName = "group1",
                UserId = "user1"
            };
        }
        // </snippet_remove_from_group>
    }
}

发送给用户

可以设置 SignalR 消息的用户 ID,以便将消息只发送给已针对某个用户进行身份验证的连接 。

示例 function.json:

{
  "type": "signalR",
  "name": "outRMessages",
  "hubName": "<hub_name>",
  "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
  "direction": "out"
}

JavaScript 代码如下所示:

module.exports = async function (context, req) {
    context.bindings.signalRMessages  = [{
        // message will only be sent to this user ID
        "userId": "userId1",
        "target": "newMessage",
        "arguments": [ req.body ]
    }];
};

完整的 PowerShell 示例处于待定状态。

下面是 Python 代码:

def main(req: func.HttpRequest, outMessages: func.Out[str]) -> func.HttpResponse:
    message = req.get_json()
    outMessage.set(json.dumps({
        #message will only be sent to this user ID
        'userId': 'userId1',
        'target': 'newMessage',
        'arguments': [ message ]
    }))

发送给用户

可以设置 SignalR 消息的用户 ID,以便将消息只发送给已针对某个用户进行身份验证的连接 。

@FunctionName("sendMessage")
@SignalROutput(name = "$return", hubName = "chat")
public SignalRMessage sendMessage(
        @HttpTrigger(
            name = "req",
            methods = { HttpMethod.POST },
            authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req) {

    SignalRMessage message = new SignalRMessage();
    message.userId = "userId1";
    message.target = "newMessage";
    message.arguments.add(req.getBody());
    return message;
}

发送给组

可以设置 SignalR 消息的组名称,以便将消息只发送给已添加到某个组的连接 。

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.IO;
using System.Linq;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;

namespace SampleApp
{
    /// <summary>
    /// The class is the same as SignalROutputBindingFunctions except the comments. Just keep the original one because the learn website refers to it.
    /// </summary>
    public static class SignalROutputBindingFunctions2
    {
        // <snippet_broadcast_to_all>
        [Function(nameof(BroadcastToAll))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction BroadcastToAll([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                // broadcast to all the connected clients without specifying any connection, user or group.
                Arguments = new[] { bodyReader.ReadToEnd() },
            };
        }
        // </snippet_broadcast_to_all>

        // <snippet_send_to_connection>
        [Function(nameof(SendToConnection))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToConnection([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                ConnectionId = "connectionToSend",
            };
        }
        // </snippet_send_to_connection>

        // <snippet_send_to_user>
        [Function(nameof(SendToUser))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToUser([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                UserId = "userToSend",
            };
        }
        // </snippet_send_to_user>

        // <snippet_send_to_group>
        [Function(nameof(SendToGroup))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                GroupName = "groupToSend"
            };
        }
        // </snippet_send_to_group>

        // <snippet_send_to_endpoint>
        [Function(nameof(SendToEndpoint))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToEndpoint(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req,
            [SignalREndpointsInput("chat", ConnectionStringSetting = "SignalRConnection")] SignalREndpoint[] endpoints)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                // Only send to primary endpoint if you have configured multiple SignalR Service instances.
                // The use of 'Endpoints' can be combined with other properties such as UserId, GroupName, ConnectionID.
                Endpoints = endpoints.Where(e => e.EndpointType == SignalREndpointType.Primary).ToArray()
            };
        }
        // </snippet_send_to_endpoint>

        // <snippet_remove_from_group>
        [Function(nameof(RemoveFromGroup))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRGroupAction RemoveFromGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            return new SignalRGroupAction(SignalRGroupActionType.Remove)
            {
                GroupName = "group1",
                UserId = "user1"
            };
        }
        // </snippet_remove_from_group>
    }
}

发送给组

可以设置 SignalR 消息的组名称,以便将消息只发送给已添加到某个组的连接 。

示例 function.json:

{
  "type": "signalR",
  "name": "signalRMessages",
  "hubName": "<hub_name>",
  "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
  "direction": "out"
}

JavaScript 代码如下所示:

module.exports = async function (context, req) {
    context.bindings.signalRMessages = [{
        // message will only be sent to this group
        "groupName": "myGroup",
        "target": "newMessage",
        "arguments": [ req.body ]
    }];
};

完整的 PowerShell 示例处于待定状态。

下面是 Python 代码:

def main(req: func.HttpRequest, outMessage: func.Out[str]) -> func.HttpResponse:
    message = req.get_json()
    outMessage.set(json.dumps({
        #message will only be sent to this group
        'groupName': 'myGroup',
        'target': 'newMessage',
        'arguments': [ message ]
    }))

发送给组

可以设置 SignalR 消息的组名称,以便将消息只发送给已添加到某个组的连接 。

@FunctionName("sendMessage")
@SignalROutput(name = "$return", hubName = "chat")
public SignalRMessage sendMessage(
        @HttpTrigger(
            name = "req",
            methods = { HttpMethod.POST },
            authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req) {

    SignalRMessage message = new SignalRMessage();
    message.groupName = "myGroup";
    message.target = "newMessage";
    message.arguments.add(req.getBody());
    return message;
}

组管理

SignalR 服务允许将用户或连接添加到组中。 然后即可将消息发送到组。 可以使用 SignalR 输出绑定来管理组。

指定 SignalRGroupActionType 以添加或删除成员。 以下示例从组中删除用户。

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.IO;
using System.Linq;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;

namespace SampleApp
{
    /// <summary>
    /// The class is the same as SignalROutputBindingFunctions except the comments. Just keep the original one because the learn website refers to it.
    /// </summary>
    public static class SignalROutputBindingFunctions2
    {
        // <snippet_broadcast_to_all>
        [Function(nameof(BroadcastToAll))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction BroadcastToAll([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                // broadcast to all the connected clients without specifying any connection, user or group.
                Arguments = new[] { bodyReader.ReadToEnd() },
            };
        }
        // </snippet_broadcast_to_all>

        // <snippet_send_to_connection>
        [Function(nameof(SendToConnection))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToConnection([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                ConnectionId = "connectionToSend",
            };
        }
        // </snippet_send_to_connection>

        // <snippet_send_to_user>
        [Function(nameof(SendToUser))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToUser([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                UserId = "userToSend",
            };
        }
        // </snippet_send_to_user>

        // <snippet_send_to_group>
        [Function(nameof(SendToGroup))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                GroupName = "groupToSend"
            };
        }
        // </snippet_send_to_group>

        // <snippet_send_to_endpoint>
        [Function(nameof(SendToEndpoint))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRMessageAction SendToEndpoint(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req,
            [SignalREndpointsInput("chat", ConnectionStringSetting = "SignalRConnection")] SignalREndpoint[] endpoints)
        {
            using var bodyReader = new StreamReader(req.Body);
            return new SignalRMessageAction("newMessage")
            {
                Arguments = new[] { bodyReader.ReadToEnd() },
                // Only send to primary endpoint if you have configured multiple SignalR Service instances.
                // The use of 'Endpoints' can be combined with other properties such as UserId, GroupName, ConnectionID.
                Endpoints = endpoints.Where(e => e.EndpointType == SignalREndpointType.Primary).ToArray()
            };
        }
        // </snippet_send_to_endpoint>

        // <snippet_remove_from_group>
        [Function(nameof(RemoveFromGroup))]
        [SignalROutput(HubName = "chat", ConnectionStringSetting = "SignalRConnection")]
        public static SignalRGroupAction RemoveFromGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
        {
            return new SignalRGroupAction(SignalRGroupActionType.Remove)
            {
                GroupName = "group1",
                UserId = "user1"
            };
        }
        // </snippet_remove_from_group>
    }
}

注意

若要正确绑定 ClaimsPrincipal,必须已经在 Azure Functions 中配置身份验证设置。

组管理

SignalR 服务允许将用户或连接添加到组中。 然后即可将消息发送到组。 可以使用 SignalR 输出绑定来管理组。

定义输出绑定的示例 function.json:

{
    "type": "signalR",
    "name": "signalRGroupActions",
    "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
    "hubName": "chat",
    "direction": "out"
}

以下示例将用户添加到组。

module.exports = async function (context, req) {
  context.bindings.signalRGroupActions = [{
    "userId": req.query.userId,
    "groupName": "myGroup",
    "action": "add"
  }];
};

以下示例从组中删除用户。

module.exports = async function (context, req) {
  context.bindings.signalRGroupActions = [{
    "userId": req.query.userId,
    "groupName": "myGroup",
    "action": "remove"
  }];
};

完整的 PowerShell 示例处于待定状态。

以下示例将用户添加到组。

def main(req: func.HttpRequest, action: func.Out[str]) -> func.HttpResponse:
    action.set(json.dumps({
        'userId': 'userId1',
        'groupName': 'myGroup',
        'action': 'add'
    }))

以下示例从组中删除用户。

def main(req: func.HttpRequest, action: func.Out[str]) -> func.HttpResponse:
    action.set(json.dumps({
        'userId': 'userId1',
        'groupName': 'myGroup',
        'action': 'remove'
    }))

组管理

SignalR 服务允许将用户或连接添加到组中。 然后即可将消息发送到组。 可以使用 SignalR 输出绑定来管理组。

以下示例将用户添加到组。

@FunctionName("addToGroup")
@SignalROutput(name = "$return", hubName = "chat")
public SignalRGroupAction addToGroup(
        @HttpTrigger(
            name = "req",
            methods = { HttpMethod.POST },
            authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req,
        @BindingName("userId") String userId) {

    SignalRGroupAction groupAction = new SignalRGroupAction();
    groupAction.action = "add";
    groupAction.userId = userId;
    groupAction.groupName = "myGroup";
    return action;
}

以下示例从组中删除用户。

@FunctionName("removeFromGroup")
@SignalROutput(name = "$return", hubName = "chat")
public SignalRGroupAction removeFromGroup(
        @HttpTrigger(
            name = "req",
            methods = { HttpMethod.POST },
            authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req,
        @BindingName("userId") String userId) {

    SignalRGroupAction groupAction = new SignalRGroupAction();
    groupAction.action = "remove";
    groupAction.userId = userId;
    groupAction.groupName = "myGroup";
    return action;
}

特性

进程内独立工作进程 C# 库都使用特性来定义函数。 C# 脚本改为使用 function.json 配置文件

下表说明了 SignalROutput 特性的属性。

Attribute 属性 说明
HubName 此值必须设置为 SignalR 中心(将为其生成连接信息)的名称。
ConnectionStringSetting 包含 SignalR 服务连接字符串(默认为 AzureSignalRConnectionString)的应用设置的名称。

批注

下表说明了 SignalROutput 批注的受支持的设置。

设置 说明
name 变量名称,在连接信息对象的函数代码中使用。
hubName 此值必须设置为 SignalR 中心(将为其生成连接信息)的名称。
connectionStringSetting 包含 SignalR 服务连接字符串(默认为 AzureSignalRConnectionString)的应用设置的名称。

配置

下表解释了在 function.json 文件中设置的绑定配置属性。

“function.json”属性 说明
type 必须设置为 signalR
direction 必须设置为 out
name 变量名称,在连接信息对象的函数代码中使用。
hubName 此值必须设置为 SignalR 中心(将为其生成连接信息)的名称。
connectionStringSetting 包含 SignalR 服务连接字符串(默认为 AzureSignalRConnectionString)的应用设置的名称。

在本地开发时,请将应用程序设置添加到 Values 集合的 local.settings.json 文件

后续步骤