Blazor Web Assembly 不支持传统的 Session 变量。取而代之的是使用 LocalStorage 或者 IndexedDB 实现与 Session 变量类似的功能。
以下是使用 LocalStorage 实现的代码示例:
using Microsoft.JSInterop;
using System.Threading.Tasks;
public interface ISessionStorageService
{
Task GetItemAsync(string key);
Task SetItemAsync(string key, T value);
Task RemoveItemAsync(string key);
}
public class SessionStorageService : ISessionStorageService
{
private readonly IJSRuntime _jsRuntime;
public SessionStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task GetItemAsync(string key)
{
return await _jsRuntime.InvokeAsync("sessionStorage.getItem", key);
}
public async Task SetItemAsync(string key, T value)
{
await _jsRuntime.InvokeVoidAsync("sessionStorage.setItem", key, value);
}
public async Task RemoveItemAsync(string key)
{
await _jsRuntime.InvokeVoidAsync("sessionStorage.removeItem", key);
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped();
}
@page "/counter"
@using System.Threading.Tasks
@inject ISessionStorageService SessionStorage
Counter
Current count: @currentCount
@code {
private int currentCount = 0;
private async Task IncrementCount()
{
currentCount++;
await SessionStorage.SetItemAsync("count", currentCount);
}
protected override async Task OnInitializedAsync()
{
currentCount = await SessionStorage.GetItemAsync("count");
}
}
上面的代码中使用了 Blazor 中的 @inject 指令将 IS