是的,可以使用 Web 存储 API 将 Asp.Net Core Web 应用程序集成到本地存储中。 Web 存储 API 提供了许多功能,包括访问本地存储、会话存储和 Cookie 存储。
以下示例演示如何将 Asp.Net Core 应用程序与浏览器本地存储集成:
public class LocalStorageService { private readonly IJSRuntime _jsRuntime;
public LocalStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime));
}
public async Task SetItem(string key, T value)
{
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", key, JsonSerializer.Serialize(value));
}
public async Task GetItem(string key)
{
var json = await _jsRuntime.InvokeAsync("localStorage.getItem", key);
return json == null ? default : JsonSerializer.Deserialize(json);
}
public async Task RemoveItem(string key)
{
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", key);
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped
@page "/" @using System.Collections.Generic @using System.Threading.Tasks @using Microsoft.AspNetCore.Components.Web @using Microsoft.JSInterop
@inject LocalStorageService LocalStorageService
@section Scripts {