Blazor服务器端的问题之一是其Singleton和Scoped服务,它的Singleton在所有用户之间共享,使其像缓存一样工作,并且范围服务在刷新时丢失,我解决了这个问题,获得了Singleton服务,不共享,如下所示: 首先,我们需要两项服务:
namespace BlazorStore9.Services
{
public class MZSingleton
{
public Dictionary<Guid, Cart> Carts { get; set; } = new Dictionary<Guid, Cart>();
}
public class MZScopedSessionID
{
public Guid SessionID { get; set; }
}
}
然后分别将它们注册为Singleton和Scoped,并将它们注入到“布局”页面和其他需要它的页面或组件中,以下是“布局”页面,该页面使用“本地存储”存储和检索sessionID:
@inject IJsInterop jsInterop
@inject MZSingleton mzSingleton
@inject MZScopedSessionID sessionID
@code
{
private BlazorStore9.Services.Cart cart = null;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
#region some imp codes
if (firstRender)
{
string SessionIDString = await jsInterop.GetAccessToken("SessionID");
if (string.IsNullOrEmpty(SessionIDString) || !Guid.TryParse(SessionIDString, out Guid theGuid))
{
Guid id = Guid.NewGuid();
await jsInterop.SaveAccessToken("SessionID", id.ToString());
sessionID.SessionID = id;
mzSingleton.Carts[sessionID.SessionID] = new Cart();
}
else
{
sessionID.SessionID = Guid.Parse(SessionIDString);
if (!mzSingleton.Carts.ContainsKey(sessionID.SessionID))
mzSingleton.Carts[sessionID.SessionID] = new Cart();
}
cart = mzSingleton.Carts[sessionID.SessionID];
}
}
然后在每个页面或组件中都有
@inject MZSingleton mzSingleton
@inject MZScopedSessionID sessionID
@code
{
private Cart cart = null;
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
cart = mzSingleton.Carts[sessionID.SessionID];
}
}
我的问题是,此方法是否可以安全地用于身份验证?在这里,我只显示了一个购物车,它不能保证安全,但是出于身份验证的目的呢?