Azure SignalR服务实现.NET 6 Azure函数隔离进程

mo49yndu  于 2023-06-30  发布在  .NET
关注(0)|答案(1)|浏览(106)

我尝试在Azure函数中使用隔离进程实现Azure SignalR服务。到目前为止,它的工作对我来说还不错。我读了微软的文档,其中提到要注册任何输出绑定,我需要为其创建azure函数。下面是我的代码:

[Function("BroadcastToAll")]
[SignalROutput(HubName = "demohub", ConnectionStringSetting = "AzureSignalRConnectionString")]
public SignalRMessageAction BroadcastToAll([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
{
    try
    {
        using var bodyReader = new StreamReader(req.Body);
        var d = bodyReader.ReadToEnd();
      return  new SignalRMessageAction("newMessage")
        {
            // broadcast to all the connected clients without specifying any connection, user or group.
            Arguments = new[] { d },
        };
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

我的问题是返回类型必须是SignalRMessageAction。如何让它的返回类型像HttpResponseData

s4n0splo

s4n0splo1#

返回类型必须为SignalRMessageAction
返回类型不一定是SignalRMessageAction

  • 我们可以根据我们的需求使用MSDoc中提到的任何返回类型。

我怎么能让它的返回类型像HttpResponseData
当我们使用SignalR创建Azure Function时,默认函数代码将使用HttpResponseData创建。

我的示例代码:

[Function("negotiate")]
 public HttpResponseData Negotiate(
     [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req,
     [SignalRConnectionInfoInput(HubName = "HubValue")] MyConnectionInfo connectionInfo)
 {
     _logger.LogInformation($"SignalR Connection URL = '{connectionInfo.Url}'");

     var response = req.CreateResponse(HttpStatusCode.OK);
     response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
     response.WriteString($"Connection URL = '{connectionInfo.Url}'");
     
     return response;
 }
  • 上面的默认代码返回HttpResponseData

local.settings.json文件中添加SignalRConnectionString。

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "AzureSignalRConnectionString": "Endpoint=https://****.service.signalr.net;AccessKey=****;Version=1.0;"
  }
}
  • 我的.csproj文件:*
<ItemGroup>
    <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.14.1" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.12" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.SignalRService" Version="1.2.2" />
    <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.10.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SignalRService" Version="1.10.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="6.0.1" />
  </ItemGroup>

相关问题