以下是在 Program.cs 文件中配置支持 WebSockets 的代码示例:
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
using System;
var builder = WebApplication.CreateBuilder(args);
// ...
builder.Services.AddSignalR();
var app = builder.Build();
// ...
app.UseEndpoints(endpoints =>
{
endpoints.MapFallbackToFile("index.html");
endpoints.MapHub("/myhub");
});
// ...
using Microsoft.JSInterop;
using System;
using System.Threading.Tasks;
public class MyComponent : ComponentBase
{
[Inject]
IJSRuntime JSRuntime { get; set; }
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary AdditionalAttributes { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JSRuntime.InvokeVoidAsync("mycustomjslibrary.init", AdditionalAttributes);
}
}
}
using System.Threading.Tasks;
using Microsoft.JSInterop;
public class MyComponent : ComponentBase
{
[Inject]
IJSRuntime JSRuntime { get; set; }
protected override async Task OnInitializedAsync()
{
try
{
// Disable some aspect of SignalR to obtain better performance
var result = await JSRuntime.InvokeAsync