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

我对 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 <======

         });
     }
 } 

https://stackoverflow.com/questions/60239701/

相关文章:

xaml - 如何在使用 xamarin shell 时更改状态栏颜色

amazon-web-services - AWS Lambda 不等待代码上传到 Terrafor

graphql - Apollo Graphql : Rename schema for backw

sql-server - SSIS:发生 OLE DB 错误。错误代码 0x80004005,对方过

ios - 如何不从照片库 iOS 中获取屏幕截图

javascript - 雅格斯 : access processed argv in fail f

google-cloud-functions - ingressSettings = ALLOW_I

node.js - Lambda 失败并显示 "Cannot find module..."

swift - PHPhotoLibrary 出错,无法保存视频

r - 无法在 R Studio 中安装包