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();
相关推荐
星星电灯猴10 分钟前
iOS 性能调试全流程:从 Demo 到产品化的小团队实战经验
后端
程序无bug18 分钟前
手写Spring框架
java·后端
JohnYan20 分钟前
模板+数据的文档生成技术方案设计和实现
javascript·后端·架构
全干engineer32 分钟前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Da_秀35 分钟前
软件工程中耦合度
开发语言·后端·架构·软件工程
蓝易云1 小时前
Qt框架中connect()方法的ConnectionType参数使用说明 点击改变文章字体大小
linux·前端·后端
a_Dragon11 小时前
Spring Boot多环境开发-Profiles
java·spring boot·后端·intellij-idea
用户8324951417321 小时前
Maven 项目打包:实现业务代码与第三方依赖分离
后端
发仔1231 小时前
解析实时推荐系统的数据流向
后端
ChinaRainbowSea1 小时前
补充:问题:CORS ,前后端访问跨域问题
java·spring boot·后端·spring