问题描述
我对Blazor Server还是陌生的,并且已经设法调整默认的.Net核心项目模板来创建自己的index.html页面。
我的index.html页面连接到辅助signalR集线器,以从后端Kafka主题接收一些信息。
使用Blazor Server,如何捕获页面的关闭事件(以响应浏览器选项卡关闭,关闭浏览器或访问另一个链接),以便我可以关闭与辅助signalR集线器的连接?
namespace WebApp.Pages
{
public partial class Index : ComponentBase,IAsyncdisposable
{
private HubConnection hubConnection;
public bool IsConnected => hubConnection.State == HubConnectionState.Connected;
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public IMotionDetectionRepository Repository { get; set; }
[Inject]
public ILogger<MotionDetectionConverter> LoggerMotionDetection { get; set; }
[Inject]
public ILogger<MotionInfoConverter> LoggerMotionInfo { get; set; }
[Inject]
public ILogger<JsonVisitor> LoggerjsonVisitor { get; set; }
[Inject]
public ILogger<Index> Logger { get; set; }
/// <summary>
/// dispose of the signalR connection when page disposed
/// </summary>
public async ValueTask disposeAsync()
{
if (hubConnection != null)
{
Logger.Log@R_725_4045@ion("disposing signalR connection...");
await hubConnection.disposeAsync();
}
}
protected override async Task OnInitializedAsync()
{
var hubUrl = NavigationManager.BaseUri.TrimEnd('/') + "/motionhub";
try
{
hubConnection = new HubConnectionBuilder()
.WithUrl(hubUrl)
.ConfigureLogging(logging =>
{
logging.AddConsole();
logging.AddFilter("Microsoft.AspNetCore.SignalR",LogLevel.@R_725_4045@ion);
})
.AddJsonProtocol(options =>
{
options.PayloadSerializerOptions = JsonConvertersFactory.CreateDefaultJsonConverters(LoggerMotionDetection,LoggerMotionInfo,LoggerjsonVisitor);
})
.Build();
hubConnection.On<MotionDetection>("ReceiveMotionDetection",ReceiveMessage);
hubConnection.Closed += CloseHandler;
await hubConnection.StartAsync();
Logger.Log@R_725_4045@ion("Index Razor Page initialised,listening on signalR hub url => " + hubUrl.ToString());
}
catch (Exception e)
{
Logger.LogError(e,"Encountered exception => " + e);
}
}
/// <remarks>
/// If this event was triggered from a connection error,the Exception that occurred will be
/// passed in as the sole argument to this handler.
/// If this event was triggered intentionally by either the client or server,then the argument
/// will be null.
/// </remarks>
private Task CloseHandler(Exception exception)
{
if (exception == null)
{
Logger.Log@R_725_4045@ion("signalR client connection closed");
}
else
{
Logger.Log@R_725_4045@ion($"signalR client closed due to error => {exception.Message}");
}
return Task.CompletedTask;
}
private void ReceiveMessage(MotionDetection message)
{
try
{
Logger.Log@R_725_4045@ion("Motion detection message received");
Repository.AddItem(message);
StateHasChanged();
}
catch (Exception ex)
{
Logger.LogError(ex,"An exception was encountered => " + ex.ToString());
}
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)