SW2*_*702 6 c# asp.net signalr blazor blazor-server-side
我有一个 blazor Web 程序集项目和一个信号 r 服务项目,我想在添加学生时调用对 ui 的更改。目前我必须刷新页面才能看到添加内容。
学生服务.cs
public class StudentService
{
public HubConnection connection;
public StudentServicen()
{
connection = new HubConnectionBuilder()
.WithUrl(".../StudentsHub")
.Build();
connection.StartAsync();
}
public async Task<List<Students>> GetAllStudents() =>
await connection.InvokeAsync<List<Students>>("GetAllStudents"));
public async Task<Boolean> AddStudent(StudentData student) =>
await connection.InvokeAsync<Boolean>("AddStudent", student);
}
Run Code Online (Sandbox Code Playgroud)
学生.razor
@inject StudentService StudentService
<ul >
@foreach (var student in students)
{
<li>@student.Name</li>
}
</ul>
@code {
private List<Students> students = new List<Students>();
protected override async Task OnInitializedAsync()
{
students = await StudentService.GetAllStudents();
}
Run Code Online (Sandbox Code Playgroud)
学生集中在另一个项目中。
@inject StudentService StudentService
<ul >
@foreach (var student in students)
{
<li>@student.Name</li>
}
</ul>
@code {
private List<Students> students = new List<Students>();
protected override async Task OnInitializedAsync()
{
students = await StudentService.GetAllStudents();
}
Run Code Online (Sandbox Code Playgroud)
Isa*_*aac 11
您提供了部分代码片段,因此我创建了一个小示例,该示例正在运行,并使用自定义服务访问服务器集线器,并将值返回到注入自定义服务的 razor 组件。
请注意,当您使用服务和回调时,您必须使用 InvokeAsync 方法,该方法分派到 Blazor 的 SynchronizationContext,这是一个强制执行单个逻辑线程的对象。
这是完整的代码,复制并测试它,看看它是否可以帮助您的应用程序...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.SignalR.Client;
namespace BlazorSignalRApp.Client
{
public class UserService
{
public event Action Notify;
public string User { get; set; }
public string Message { get; set; }
HubConnection hubConnection;
public UserService(NavigationManager navigationManager)
{
hubConnection = new HubConnectionBuilder()
.WithUrl(navigationManager.ToAbsoluteUri("/chatHub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user,
message) =>
{
User = user;
Message = message;
if (Notify != null)
{
Notify?.Invoke();
}
});
hubConnection.StartAsync();
hubConnection.SendAsync("SendMessage", null, null);
}
public void Send(string userInput, string messageInput) =>
hubConnection.SendAsync("SendMessage", userInput, messageInput);
public bool IsConnected => hubConnection.State ==
HubConnectionState.Connected;
}
}
Run Code Online (Sandbox Code Playgroud)
@page "/"
@inject UserService UserService
@implements IDisposable
<div>
<label for="userInput">User:</label>
<input id="userInput" @bind="@userInput" />
</div>
<div class="form-group">
<label for="messageInput">Message:</label>
<input id="messageInput" @bind="@messageInput" />
</div>
<button @onclick="@(() => UserService.Send(userInput, messageInput))"
disabled="@(!UserService.IsConnected)">Send Message</button>
<hr />
<ul id="messagesList">
@foreach (var message in messages)
{
<li>@message</li>
}
</ul>
@code {
List<string> messages = new List<string>();
string userInput;
string messageInput;
protected override void OnInitialized()
{
UserService.Notify += OnNotify;
}
public void OnNotify()
{
if (!string.IsNullOrEmpty(UserService.User))
{
var encodedMsg = UserService.User + " says " +
UserService.Message;
messages.Add(encodedMsg);
}
InvokeAsync(() =>
{
StateHasChanged();
});
}
public void Dispose()
{
UserService.Notify -= OnNotify;
}
}
Run Code Online (Sandbox Code Playgroud)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace BlazorSignalRApp.Server.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Blazor.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Components;
namespace BlazorSignalRApp.Client
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddSingleton<UserService>();
builder.RootComponents.Add<App>("app");
await builder.Build().RunAsync();
}
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助...