I am trying to build a test app so that my HTML page can send a message to an long running method on an Azure function via SignalR, and the long running function can use SignalR to report progress back to the HTML page.
Does anyone know how to do this? I am using .NET Core 3.1 for the function and the Azure SignalR service in serverless mode. I have looked around on the web but it all seems to be about chat whereas I would have thought this is quite a common requirement.
This is what I have so far...
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace AzureSignalRFunctionTest
{
public static class Function1
{
// Input Binding
[FunctionName("negotiate")]
public static SignalRConnectionInfo Negotiate(
[HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
[SignalRConnectionInfo(HubName = "TestHub")] SignalRConnectionInfo connectionInfo)
{
return connectionInfo;
}
// Trigger Binding
[FunctionName("longrunningtask")]
public static void LongRunningTask([SignalRTrigger("longrunningtask", "messages", "SendMessage")] InvocationContext invocationContext, [SignalRParameter] string message, ILogger logger)
{
logger.LogInformation($"Receive {message} from {invocationContext.ConnectionId}.");
// what to put here?
//var clients = invocationContext.GetClientsAsync().Result;
//ReportProgress(invocationContext.ConnectionId, "Progress", ...);
// Simulate Long running task
System.Threading.Thread.Sleep(30000);
// ReportProgress etc
}
// Output Binding
[FunctionName("reportprogress")]
public static Task ReportProgress(string connectionId, string message,
[SignalR(HubName = "TestHub")] IAsyncCollector<SignalRMessage> signalRMessages)
{
return signalRMessages.AddAsync(
new SignalRMessage
{
ConnectionId = connectionId,
Target = "reportProgress",
Arguments = new[] { message }
});
}
}
}