Asp.NetCoreWeb应用程序可以集成本地存储吗?
创始人
2024-09-18 11:00:48
0

是的,可以使用 Web 存储 API 将 Asp.Net Core Web 应用程序集成到本地存储中。 Web 存储 API 提供了许多功能,包括访问本地存储、会话存储和 Cookie 存储。

以下示例演示如何将 Asp.Net Core 应用程序与浏览器本地存储集成:

  1. 创建一个名为“LocalStorageService”的服务类。

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);
}

}

  1. 在 Startup.cs 中注册服务。

public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor(); services.AddScoped(); }

  1. 在 Razor 页面中使用服务。

@page "/" @using System.Collections.Generic @using System.Threading.Tasks @using Microsoft.AspNetCore.Components.Web @using Microsoft.JSInterop

@inject LocalStorageService LocalStorageService

Local Storage Example

    @foreach(var item in items) {
  • @item
  • }

@section Scripts {