我在Web应用程序Blazor服务器端工作。我得到错误时,应用会话超时达到20分钟,然后应用程序将重定向到登录页面。
此代码块发生错误
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
});
services.AddScoped<ISession>(_ => _.GetRequiredService<IHttpContextAccessor>().HttpContext.Session);
误差
Category: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost
EventId: 111
SpanId: b5f359c71bdf98dd
TraceId: 55c402b51115a74fe957d0762f8e004f
ParentId: 0000000000000000
RequestId: 800002a3-0000-f500-b63f-84710c7967bb
RequestPath: /_blazor
TransportConnectionId: GD0qeN4kpoisoFqdq7Lm_Q
Unhandled exception in circuit 'fsJjR_i80e4-G8BcnIas7mkmnqTlTY5vpTXVNEzo_Rg'.
Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at UC.AppRepository.UI.Startup.<>c.<ConfigureServices>b__4_1(IServiceProvider _) in D:\test repository\BackupBlazor\UC.AppRepository.UI\Startup.cs:line 67
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.AspNetCore.Components.ComponentFactory.<>c__DisplayClass7_0.<CreateInitializer>g__Initialize|1(IServiceProvider serviceProvider, IComponent component)
at Microsoft.AspNetCore.Components.ComponentFactory.PerformPropertyInjection(IServiceProvider serviceProvider, IComponent instance)
at Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider serviceProvider, Type componentType)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateChildComponentOnFrame(RenderTreeFrame& frame, Int32 parentComponentId)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(DiffContext& diffContext, Int32 frameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(DiffContext& diffContext, Int32 newFrameIndex)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& diffContext, Int32 oldStartIndex, Int32 oldEndIndexExcl, Int32 newStartIndex, Int32 newEndIndexExcl)
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, Int32 componentId, ArrayRange`1 oldTree, ArrayRange`1 newTree)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
详细信息
我在20分钟后应用会话超时
1 -在wwwroot/js
文件上创建具有checkSessionTimeout
功能的js
function checkSessionTimeout(currentUrl) {
var sessionTimeout = 20 * 60 * 1000; // 2 minutes in milliseconds
var lastActivity = new Date(Date.parse(sessionStorage.getItem("LastActivity"))); // get the last activity time from the client-side session
if (new Date() - lastActivity > sessionTimeout) {
/*console.log("reach 2 minutes")*/
sessionStorage.clear(); // clear the session storage
}
else
{
setTimeout(function () { checkSessionTimeout(currentUrl); }, 1000); // check again in 1 second
}
}
checkSessionTimeout(window.document. writeln);
第2页。剃刀
@inject ISession Session;
protected override void OnInitialized()
{
DateTime now = DateTime.Now;
string nowString = now.ToString("yyyy-MM-ddTHH:mm:ss");
JS.InvokeVoidAsync("sessionStorage.setItem", "LastActivity", now);
}
3 -组件加载后调用函数checkSessionTimeout
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var lastActivity = Session.GetInt32("LastActivity");
if ( TimeSpan.FromTicks(DateTime.Now.Ticks - lastActivity.Value) < TimeSpan.FromMinutes(20))
{
navigationManager.NavigateTo("/Login/Login");
return;
}
}
4-on _host文件在正文的最后一行添加以下内容:
<script src="~/assets/js/checksessiontimeout.js"></script>
5-启动类
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddHttpClient();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSession();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
});
services.AddScoped<ISession>(_ => _.GetRequiredService<IHttpContextAccessor>().HttpContext.Session); line 67 that give me error
}
那么如何解决或防止这种错误的发生呢?
更新文章
那么您能告诉我如何在不使用HTTP上下文情况下实现会话超时吗?
你能用代码告诉我吗
如果我避免使用HTTP上下文,那么有什么解决方案来实现它
1条答案
按热度按时间6psbrbz91#
暂时忘记在Blazor服务器中使用Session。
Blazor使用websockets,而不是http reqests/response模型。因此:
1.你不能在Blazor中使用HttpContextAccessor,因为HttpContext并不总是可用的。当你打开Blazor应用程序时,它通常是有效的,但后来,它返回null。
1.当没有HttpContext时,就没有Session。
我可以想象一些黑客,将允许您使用会话,但我会坚持什么是支持的。
此外,请注意blazor会话与http会话不同。ASP.NET核心会话)