gpt4 book ai didi

c# - Blazor 在 X 量空闲时间后做某事

转载 作者:行者123 更新时间:2023-12-05 08:06:35 27 4
gpt4 key购买 nike

我对 blazor 和 core 还很陌生。

我的问题是我有一个以 API 为中心的应用程序,它将对 api 进行登录调用并获取 JWT token 。我需要找到一种方法在一段时间空闲后注销用户并清除我保存的 JWT token 。

我在某处读到他们从未在 Blazor 中添加检测空闲时间的方法,但我很好奇是否有人对此有解决方案。

最佳答案

使用 JavaScript onmousemove 和 onkeypress 事件触发 Razor 组件中的 Timer 功能可以识别用户是活跃还是不活跃。如果用户没有执行任何 onmousemove 或 onkeypress 事件,则认为用户处于非事件状态,并且在一定的 TimeInterval 后调用 Timer 函数以[执行您想要执行的任何操作。

  1. 打开 _Host.cshtml 并更新如下。在 JavaScript 中调用 onmousemove 和 onkeypress 属性函数来触发 Razor 组件中的 Timer 函数。

<body>
// . . .
<script>
function timeOutCall(dotnethelper) {
document.onmousemove = resetTimeDelay;
document.onkeypress = resetTimeDelay;

function resetTimeDelay() {
dotnethelper.invokeMethodAsync("TimerInterval");
}
}
</script>
</body>

  1. 现在打开 MainLayout.razor 并调用 Timer 方法来识别用户是否处于事件状态。当发现用户处于非事件状态时,您可以在方法中添加代码
@using System.Timers
@inject IJSRuntime JSRuntime

// . . .
@code {
private Timer timerObj;

protected override async Task OnInitializedAsync()
{
// Set the Timer delay.
timerObj = new Timer(7000);
timerObj.Elapsed += UpdateTimer;
timerObj.AutoReset = false;
// Identify whether the user is active or inactive using onmousemove and onkeypress in JS function.
await JSRuntime.InvokeVoidAsync("timeOutCall", DotNetObjectReference.Create(this));
}

[JSInvokable]
public void TimerInterval()
{
// Resetting the Timer if the user in active state.
timerObj.Stop();
// Call the TimeInterval to logout when the user is inactive.
timerObj.Start();
}

private void UpdateTimer(Object source, ElapsedEventArgs e)
{
InvokeAsync(async() => {

// ======> DO WHATEVER YOU WANT TO DO HERE <======

});
}
}

关于c# - Blazor 在 X 量空闲时间后做某事,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60239701/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com