当我启动Blazor服务器应用程序时,我可以在SignalR服务中看到8台服务器已连接.我不明白为什么. 我的目标是MyRazorPage能够在不创建太多(不必要的?!)服务器的情况下发送和接收(从它自己或某个Azure函数)SignalR消息.

下面是我的代码,下面是我正在使用的DI服务注册:

100

MyRazorPage.razor

@inject IHubConnectionFactory HubConnectionFactory // see HubConnectionFactory.cs below

MyRazorPage.razor.cs

public sealed partial class MyRazorPage
{
    private HubConnection _hubConnection;
    
    public async ValueTask DisposeAsync()
    {
        if (_hubConnection is not null)
        {
            _hubConnection.Remove("MyMethodName");
            await _hubConnection.DisposeAsync();
        }
    }
    
    private async Task HandleHubMessageReceived(ResultDto result)
    {
        // handle received result
    }
    
    private Task SendMessage()
    {
        // ... 
        await _hubConnection.SendAsync("MethodName", new ResultDto(Guid.Parse(CustomerId), ResultEnum.Success));        
    }
    
    protected override async Task OnInitializedAsync()
    {  
        _hubConnection = HubConnectionFactory.CreateHubConnection();
        await _hubConnection.StartAsync(CancellationToken);
        _hubConnection.On<ResultDto>("MyMethodName", HandleHubMessageReceived);
    }   
}

100

Package references

<PackageReference Include="Microsoft.Azure.SignalR" Version="1.24.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.1" />

appsettings.json

"Azure": {
   "SignalR": {
     "Enabled": "true",
     "ConnectionString": "Endpoint=URL;AccessKey=KEY;Version=1.0;"
   },
 "SIGNALR_REFRESH_BILLING_PAGE_URI": "https://localhost:44362/MyHub",

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.AddSignalRHubConnection(config =>{
               config.ConnectionString = Configuration["SIGNALR_REFRESH_BILLING_PAGE_URI"] ?? 
               string.Empty;
               });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);

    if (!env.IsProduction())
    {
        app.UseDeveloperExceptionPage();
        app.UseMigrationsEndPoint();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseCookiePolicy();
    
    app.UseEndpoints(endpoints =>
                     {
                         endpoints.MapControllers();
                         endpoints.MapBlazorHub();
                         endpoints.MapRazorPages();
                         endpoints.MapFallbackToPage("/_Host");
                         endpoints.MapHub<MyHub>($"/{MyHub.HubName}");
                     });
}

HubConnectionFactory.cs

public class HubConnectionFactory : IHubConnectionFactory
{
    private readonly SignalREndpointConfiguration _configuration;
    
    public HubConnectionFactory(IOptions<SignalREndpointConfiguration> configuration) => _configuration = configuration.Value;
    
    public HubConnection CreateHubConnection()
    {
        return new HubConnectionBuilder()
               .WithUrl(_configuration.ConnectionString)
               .Build();
    }  
}

MyHub.cs

public class MyHub : Hub
{
    public const string HubName = "MyHub";

    public async Task SendMessage(ResultDto dto)
    {
        await Clients.All.SendAsync("MyMethodName", dto);
    }
}

我还try 了以下几种方法,但都没有成功:

Approach Result
Removed "Azure setting" from appsettings.json HandleHubMessageReceived is not invoked anymore.
Added services.AddCors() to ConfigureServices in Startup.cs and app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin() to Startup.Configure() No difference

推荐答案

我可以在SignalR服务中看到8台服务器已连接.我不明白为什么.

enter image description here

That's what you're talking about, right?

这是服务器连接,而不是服务器.

这是关于How connections are counted人的官方文件.

And server_connections_count = 1 instance * 2 hubs * 5 (default value).
                                                     = 10

提示:默认值为5-->;InitialHubServerConnectionCount

如果您想减少连接数量,可以参考官方文档.

Configure options

100

应该会有延迟,在Azure门户的图表中,统计数据可能与时间跨度有关,所以你看到的数据可能会有轻微的偏差,你可以通过查看更详细的统计数据来判断.

Csharp相关问答推荐

将实例绑定方法传递到列表foreach

Microsoft.AspNetCore.Mvc. Controller Base.用户:属性或索引器Controller Base.用户无法分配给--它是只读的

C#类主构造函数中的调试参数

属性getter和setter之间的空性不匹配?

System.Text.Json数据化的C#类映射

只有第一个LINQ.Count()语句有效

Unix上的.NET(核心):.NET意外地未看到通过P/Invoke系统调用对环境变量进行的进程内修改

在不添加不必要的尾随零的情况下本地化浮点型?

从VS调试器而不是测试资源管理器运行的调试NUnitDotNet测试

在implementationFactory中避免循环依赖

如何允许数组接受多个类型?

源代码生成器:CS8795分部方法';Class1.GetS2(字符串)';必须有实现部分,因为它有可访问性修饰符?

Celler ArgumentExpression是否期望在所有情况下都捕获允许空值的运算符?

如何在.NET MAUI中最大化GraphicsView的大小?

我找不到ASP.NET Web应用程序(.NET框架).已 Select .NET框架项目和项模板以及此组件(&Q;)

try 创建一个C#程序,该程序使用自动实现的属性、覆盖ToString()并使用子类

WPF如何获取有关从一个视图模型更改另一个视图模型的信息

游戏对象走向不同的方向

使用Try-Catch-Finally为API端点处理代码--有什么缺点?

根据运行时值获取泛型类型的字典