Skip to content

Latest commit

 

History

History
656 lines (501 loc) · 19.3 KB

functions-bindings-signalr-service-output.md

File metadata and controls

656 lines (501 loc) · 19.3 KB
titledescriptionauthorms.topicms.devlangms.customms.datems.authorzone_pivot_groups
Azure Functions SignalR Service output binding
Learn about the SignalR Service output binding for Azure Functions.
Y-Sindo
reference
csharp
devx-track-csharp, devx-track-extended-java, devx-track-js, devx-track-python
03/12/2024
zityang
programming-languages-set-functions-lang-workers

SignalR Service output binding for Azure Functions

Use the SignalR output binding to send one or more messages using Azure SignalR Service. You can broadcast a message to:

  • All connected clients
  • Connected clients in a specified group
  • Connected clients authenticated to a specific user

The output binding also allows you to manage groups, such as adding a client or user to a group, removing a client or user from a group.

For information on setup and configuration details, see the overview.

Example

Broadcast to all clients

::: zone pivot="programming-language-csharp"

[!INCLUDE functions-bindings-csharp-intro-with-csx]

[!INCLUDE functions-in-process-model-retirement-note]

The following example shows a function that sends a message using the output binding to all connected clients. The newMessage is the name of the method to be invoked on each client.

:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/SignalR/SignalROutputBindingFunctions2.cs" id="snippet_broadcast_to_all":::

The following example shows a function that sends a message using the output binding to all connected clients. The target is the name of the method to be invoked on each client. The Arguments property is an array of zero or more objects to be passed to the client method.

[FunctionName("SendMessage")]publicstaticTaskSendMessage([HttpTrigger(AuthorizationLevel.Anonymous,"post")]objectmessage,[SignalR(HubName="hubName1")]IAsyncCollector<SignalRMessage>signalROutput){returnsignalROutput.AddAsync(newSignalRMessage{Target="newMessage",Arguments=new[]{message}});}

::: zone-end ::: zone pivot="programming-language-python,programming-language-powershell"

[!INCLUDE functions-bindings-signalr-output-function-json]

::: zone-end ::: zone pivot="programming-language-javascript"

const{ app, output }=require('@azure/functions');constsignalR=output.generic({type: 'signalR',name: 'signalR',hubName: 'hub',connectionStringSetting: 'AzureSignalRConnectionString',});// You can use any other trigger type instead.app.http('broadcast',{methods: ['GET'],authLevel: 'anonymous',extraOutputs: [signalR],handler: (request,context)=>{context.extraOutputs.set(signalR,{"target": "newMessage","arguments": [request.body]});}});

[!INCLUDE functions-bindings-signalr-output-function-json]

Here's the JavaScript code:

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

::: zone-end ::: zone pivot="programming-language-powershell"

Complete PowerShell examples are pending. ::: zone-end ::: zone pivot="programming-language-python"

Here's the Python code:

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

::: zone-end ::: zone pivot="programming-language-java"

@FunctionName("sendMessage") @SignalROutput(name = "$return", HubName = "hubName1") publicSignalRMessagesendMessage( @HttpTrigger( name = "req", methods = { HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req) { SignalRMessagemessage = newSignalRMessage(); message.target = "newMessage"; message.arguments.add(req.getBody()); returnmessage; }

::: zone-end

Send to a user

You can send a message only to connections that have been authenticated to a user by setting the user ID in the SignalR message.

::: zone pivot="programming-language-csharp"

:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/SignalR/SignalROutputBindingFunctions2.cs" id="snippet_send_to_user":::

[FunctionName("SendMessage")]publicstaticTaskSendMessage([HttpTrigger(AuthorizationLevel.Anonymous,"post")]objectmessage,[SignalR(HubName="hubName1")]IAsyncCollector<SignalRMessage>signalROutput){returnsignalROutput.AddAsync(newSignalRMessage{// the message will only be sent to this user IDUserId="userId1",Target="newMessage",Arguments=new[]{message}});}

::: zone-end ::: zone pivot="programming-language-python,programming-language-powershell"

[!INCLUDE functions-bindings-signalr-output-function-json]

::: zone-end

::: zone pivot="programming-language-powershell"

Complete PowerShell examples are pending. ::: zone-end ::: zone pivot="programming-language-python"

Here's the Python code:

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

::: zone-end ::: zone pivot="programming-language-java"

@FunctionName("sendMessage") @SignalROutput(name = "$return", HubName = "hubName1") publicSignalRMessagesendMessage( @HttpTrigger( name = "req", methods = { HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req) { SignalRMessagemessage = newSignalRMessage(); message.userId = "userId1"; message.target = "newMessage"; message.arguments.add(req.getBody()); returnmessage; }

::: zone-end

::: zone pivot="programming-language-javascript"

const{ app, output }=require('@azure/functions');constsignalR=output.generic({type: 'signalR',name: 'signalR',hubName: 'hub',connectionStringSetting: 'AzureSignalRConnectionString',});app.http('sendToUser',{methods: ['GET'],authLevel: 'anonymous',extraOutputs: [signalR],handler: (request,context)=>{context.extraOutputs.set(signalR,{"target": "newMessage","arguments": [request.body],"userId": "userId1",});}});

[!INCLUDE functions-bindings-signalr-output-function-json]

Here's the JavaScript code:

module.exports=asyncfunction(context,req){context.bindings.signalROutput=[{"target": "newMessage","arguments": [req.body],"userId": "userId1",}];};

::: zone-end

Send to a group

You can send a message only to connections that have been added to a group by setting the group name in the SignalR message.

::: zone pivot="programming-language-csharp"

:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/SignalR/SignalROutputBindingFunctions2.cs" id="snippet_send_to_group":::

[FunctionName("SendMessage")]publicstaticTaskSendMessage([HttpTrigger(AuthorizationLevel.Anonymous,"post")]objectmessage,[SignalR(HubName="hubName1")]IAsyncCollector<SignalRMessage>signalROutput){returnsignalROutput.AddAsync(newSignalRMessage{// the message will be sent to the group with this nameGroupName="myGroup",Target="newMessage",Arguments=new[]{message}});}

::: zone-end ::: zone pivot="programming-language-python,programming-language-powershell"

[!INCLUDE functions-bindings-signalr-output-function-json]

::: zone-end ::: zone pivot="programming-language-javascript"

const{ app, output }=require('@azure/functions');constsignalR=output.generic({type: 'signalR',name: 'signalR',hubName: 'hub',connectionStringSetting: 'AzureSignalRConnectionString',});app.http('sendToGroup',{methods: ['GET'],authLevel: 'anonymous',extraOutputs: [signalR],handler: (request,context)=>{context.extraOutputs.set(signalR,{"target": "newMessage","arguments": [request.body],"groupName": "myGroup",});}});

[!INCLUDE functions-bindings-signalr-output-function-json]

Here's the JavaScript code:

module.exports=asyncfunction(context,req){context.bindings.signalROutput=[{"target": "newMessage","arguments": [req.body],"groupName": "myGroup",}];};

::: zone-end

::: zone pivot="programming-language-powershell"

Complete PowerShell examples are pending. ::: zone-end ::: zone pivot="programming-language-python"

Here's the Python code:

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

::: zone-end ::: zone pivot="programming-language-java"

@FunctionName("sendMessage") @SignalROutput(name = "$return", HubName = "hubName1") publicSignalRMessagesendMessage( @HttpTrigger( name = "req", methods = { HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req) { SignalRMessagemessage = newSignalRMessage(); message.groupName = "myGroup"; message.target = "newMessage"; message.arguments.add(req.getBody()); returnmessage; }

::: zone-end

Group management

SignalR Service allows users or connections to be added to groups. Messages can then be sent to a group. You can use the SignalR output binding to manage groups.

::: zone pivot="programming-language-csharp"

Specify SignalRGroupActionType to add or remove a member. The following example removes a user from a group.

:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/SignalR/SignalROutputBindingFunctions2.cs" id="snippet_remove_from_group":::

Specify GroupAction to add or remove a member. The following example adds a user to a group.

[FunctionName("addToGroup")]publicstaticTaskAddToGroup([HttpTrigger(AuthorizationLevel.Anonymous,"post")]HttpRequestreq,ClaimsPrincipalclaimsPrincipal,[SignalR(HubName="hubName1")]IAsyncCollector<SignalRGroupAction>signalRGroupActions){varuserIdClaim=claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);returnsignalRGroupActions.AddAsync(newSignalRGroupAction{UserId=userIdClaim.Value,GroupName="myGroup",Action=GroupAction.Add});}

Note

In order to get the ClaimsPrincipal correctly bound, you must have configured the authentication settings in Azure Functions.

::: zone-end ::: zone pivot="programming-language-python,programming-language-powershell"

[!INCLUDE functions-bindings-signalr-output-function-json]

::: zone-end

::: zone pivot="programming-language-javascript"

const{ app, output }=require('@azure/functions');constsignalR=output.generic({type: 'signalR',name: 'signalR',hubName: 'hub',connectionStringSetting: 'AzureSignalRConnectionString',});// The following function adds a user to a groupapp.http('addUserToGroup',{methods: ['POST'],authLevel: 'anonymous',extraOutputs: [signalR],handler: (request,context)=>{context.extraOutputs.set(signalR,{"userId": req.query.userId,"groupName": "myGroup","action": "add"});}});// The following function removes a user from a groupapp.http('removeUserFromGroup',{methods: ['POST'],authLevel: 'anonymous',extraOutputs: [signalR],handler: (request,context)=>{context.extraOutputs.set(signalR,{"userId": req.query.userId,"groupName": "myGroup","action": "remove"});}});

[!INCLUDE functions-bindings-signalr-output-function-json]

Here's the JavaScript code:

The following example adds a user to a group.

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

The following example removes a user from a group.

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

::: zone-end

::: zone pivot="programming-language-powershell"

Complete PowerShell examples are pending. ::: zone-end ::: zone pivot="programming-language-python"

The following example adds a user to a group.

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

The following example removes a user from a group.

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

::: zone-end ::: zone pivot="programming-language-java"

The following example adds a user to a group.

@FunctionName("addToGroup") @SignalROutput(name = "$return", HubName = "hubName1") publicSignalRGroupActionaddToGroup( @HttpTrigger( name = "req", methods = { HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req, @BindingName("userId") StringuserId) { SignalRGroupActiongroupAction = newSignalRGroupAction(); groupAction.action = "add"; groupAction.userId = userId; groupAction.groupName = "myGroup"; returnaction; }

The following example removes a user from a group.

@FunctionName("removeFromGroup") @SignalROutput(name = "$return", HubName = "hubName1") publicSignalRGroupActionremoveFromGroup( @HttpTrigger( name = "req", methods = { HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Object> req, @BindingName("userId") StringuserId) { SignalRGroupActiongroupAction = newSignalRGroupAction(); groupAction.action = "remove"; groupAction.userId = userId; groupAction.groupName = "myGroup"; returnaction; }

::: zone-end ::: zone pivot="programming-language-csharp"

Attributes

Both in-process and isolated worker process C# libraries use attribute to define the function. C# script instead uses a function.json configuration file.

The following table explains the properties of the SignalROutput attribute.

Attribute propertyDescription
HubNameThis value must be set to the name of the SignalR hub for which the connection information is generated.
ConnectionStringSettingThe name of the app setting or settings collection that contains the SignalR Service connection string, which defaults to AzureSignalRConnectionString.

The following table explains the properties of the SignalR output attribute.

Attribute propertyDescription
HubNameThis value must be set to the name of the SignalR hub for which the connection information is generated.
ConnectionStringSettingThe name of the app setting or settings collection that contains the SignalR Service connection string, which defaults to AzureSignalRConnectionString.

::: zone-end ::: zone pivot="programming-language-java"

Annotations

The following table explains the supported settings for the SignalROutput annotation.

SettingDescription
nameVariable name used in function code for connection info object.
hubNameThis value must be set to the name of the SignalR hub for which the connection information is generated.
connectionStringSettingThe name of the app setting or settings collection that contains the SignalR Service connection string, which defaults to AzureSignalRConnectionString.

::: zone-end ::: zone pivot="programming-language-javascript,programming-language-powershell,programming-language-python"

Configuration

The following table explains the binding configuration properties that you set in the function.json file.

function.json propertyDescription
typeMust be set to signalR.
directionMust be set to out.
nameVariable name used in function code for connection info object.
hubNameThis value must be set to the name of the SignalR hub for which the connection information is generated.
connectionStringSettingThe name of the app setting or settings collection that contains the SignalR Service connection string, which defaults to AzureSignalRConnectionString.

::: zone-end

[!INCLUDE app settings to local.settings.json]

Usage

[!INCLUDE functions-azure-signalr-authorization-note]

Next steps

close