3. BlazorSignalRApp 结合使用 ASP.NET Core SignalR 和 Blazor

参考:https://learn.microsoft.com/zh-cn/aspnet/core/blazor/tutorials/signalr-blazor?view=aspnetcore-8.0&tabs=visual-studio

1.创建新项目 BlazorSignalRApp

2.添加项目依赖项

依赖项:Microsoft.AspNetCore.SignalR.Client

方式1 管理解决方案的 Nuget程序包方式安装

方式2 修改配置文件安装

添加以下代码

bash 复制代码
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.0" />
  </ItemGroup>

保存配置文件 vs 自动下载安装依赖项

3.添加Hubs->ChatHub.cs

cs 复制代码
using Microsoft.AspNetCore.SignalR;
namespace BlazorSignalRApp.Hubs;
public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

4.修改 Home.razor 组件

html 复制代码
@page "/"
@rendermode InteractiveServer
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager Navigation
@implements IAsyncDisposable

<PageTitle>Home</PageTitle>

<div class="form-group">
    <label>
        User:
        <input @bind="userInput" />
    </label>
</div>
<div class="form-group">
    <label>
        Message:
        <input @bind="messageInput" size="50" />
    </label>
</div>
<button @onclick="Send" disabled="@(!IsConnected)">Send</button>

<hr>

<ul id="messagesList">
    @foreach (var message in messages)
    {
        <li>@message</li>
    }
</ul>

@code {
    private HubConnection? hubConnection;
    private List<string> messages = new List<string>();
    private string? userInput;
    private string? messageInput;

    protected override async Task OnInitializedAsync()
    {
        hubConnection = new HubConnectionBuilder()
            .WithUrl(Navigation.ToAbsoluteUri("/chathub"))
            .Build();

        hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
        {
            var encodedMsg = $"{user}: {message}";
            messages.Add(encodedMsg);
            InvokeAsync(StateHasChanged);
        });

        await hubConnection.StartAsync();
    }

    private async Task Send()
    {
        if (hubConnection is not null)
        {
            await hubConnection.SendAsync("SendMessage", userInput, messageInput);
        }
    }

    public bool IsConnected =>
        hubConnection?.State == HubConnectionState.Connected;

    public async ValueTask DisposeAsync()
    {
        if (hubConnection is not null)
        {
            await hubConnection.DisposeAsync();
        }
    }
}

5.修改 Program.cs 项目文件

5.1 为 SignalR 中心添加服务和终结点

5.2 在处理管道的配置顶部使用响应压缩中间件

5.3 为行添加一个终结点

cs 复制代码
using BlazorSignalRApp.Components;
using BlazorSignalRApp.Hubs;
using Microsoft.AspNetCore.ResponseCompression;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

// 1. 为 SignalR 中心添加服务和终结点
builder.Services.AddResponseCompression(opts =>
{
    opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
          new[] { "application/octet-stream" });
});


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

// 2.在处理管道的配置顶部使用响应压缩中间件:
app.UseResponseCompression();

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

// 3. 为行添加一个终结点
app.MapHub<ChatHub>("/chathub");

app.Run();
相关推荐
考虑考虑4 分钟前
JDK27中的结构化并发
java·后端·java ee
修己xj1 小时前
设备数据采集中的 XPS 文件:它是什么,以及如何正确打开
后端
LucianaiB1 小时前
PGuard 实测与流式改造:我写了一套跨平台护栏网关,顺手拿 789 个标注点把三款安全头测了一遍
后端
程序员cxuan2 小时前
绝了,WorkBuddy 可以打通微信了
人工智能·后端·程序员
程序员cxuan3 小时前
再见了反重力,Google 又来搞事了
人工智能·后端·程序员
狗头大军之江苏分军4 小时前
《潮水漫过十七岁》 加一个蛋,顺便说一下我解放了
前端·后端
Captaincc4 小时前
掘金AI用量迎来重大更新!全新AI用量
前端·后端
wdfk_prog4 小时前
Wi-Fi Direct 真机实践:JOIN 建链耗时优化
服务器·asp.net·php
AAA修煤气灶刘哥5 小时前
排查一次 CI 失败,Cloudflare 怎么把六次大模型调用减到一次?
人工智能·后端·llm
vx-程序开发5 小时前
【毕设分享】05253基于Spring+Boot的作业提交与管理系统的设计与实现
java·spring boot·后端·spring·源码·课程设计·大作业