将 Azure SignalR 服务与 Azure Function 连接时出错

问题描述 投票:0回答:1

当我尝试在启动中注册信号服务时,出现以下错误。

func:无效的主机服务。Microsoft.Azure.WebJobs.Script.WebHost:以下服务注册与预期服务不匹配: 无效]服务类型:Microsoft.Extensions.Hosting.IHostedService,生命周期:单例,实现类型:Microsoft.Azure.SignalR.HeartBeat,Microsoft.Azure.SignalR,版本=1.27.0.0,文化=中性,PublicKeyToken=adb9793829ddae60。

我使用以下代码

 private IServiceCollection ConfigureServices(IServiceCollection services)
 {
    
     var temp = Environment.GetEnvironmentVariable("AzureSignalRConnectionString");
     services.AddSignalR().AddAzureSignalR(temp);
     return services;
 }```

Any suggestion to fix this ? 



I need a solution to fix this 
azure azure-signalr
1个回答
0
投票

我在进程内Azure函数中尝试了相同的操作并得到了相同的错误。

可以通过定义名为

AzureSignalRConnectionString
的环境变量来建立与 SignalR 的连接。

参考@zetawars提供的解决方案

SignalR Azure 函数默认会从

AzureSignalRConnectionString
中的固定位置
local.settings.json
选择连接。

功能代码:

[FunctionName("negotiate")]
public static SignalRConnectionInfo Negotiate(
    [HttpTrigger(AuthorizationLevel.Anonymous,"get", "post")] HttpRequest req,
    [SignalRConnectionInfo(HubName = "HubValue")] SignalRConnectionInfo connectionInfo)
{
    return connectionInfo;
}

但这可以使用以下代码在 .NET 8.0 隔离进程中实现

AddAzureSignalR

程序.cs:

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
        services.AddSignalR().AddAzureSignalR(options =>
        {
            options.ConnectionString = Environment.GetEnvironmentVariable("AzureSignalRConnectionString");
        });
        services.Configure<KestrelServerOptions>(options =>
        {
            options.AllowSynchronousIO = true;
        });
    })
    .Build();

host.Run();

local.settings.json:

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "AzureSignalRConnectionString": "<SignalR_connection_string>"
  }
}

输出:

Functions:

        negotiate: [GET,POST] http://localhost:7201/api/negotiate

For detailed output, run func with --verbose flag.
[2024-09-20T12:31:05.809Z] Executing 'Functions.negotiate' (Reason='This function was programmatically called via the host APIs.', Id=eca3f826-7265-4a6c-bcb2-89d6e329a9de)
[2024-09-20T12:31:06.538Z] Host lock lease acquired by instance ID '000000000000000000000000F72731CC'.
[2024-09-20T12:31:06.604Z] SignalR Connection URL = 'https://kpsignalr.service.signalr.net/client/?hub=hubvalue'
[2024-09-20T12:31:06.707Z] Executed 'Functions.negotiate' (Succeeded, Id=eca3f826-7265-4a6c-bcb2-89d6e329a9de, Duration=929ms)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.