深入淺出Blazor webassembly之Local storage


普通 MVC 網頁應用本地存儲會往往采用 cookie, 而 Blazor wasm 應用和其他 SPA 框架類似, 基本不使用 cookie, 通常使用的是 Local storage 或 session storage.

Local storage 和 session storage的持久化能力不同, session storage 在瀏覽器的 tab 頁關閉后, 將會自動失效, 而 Local storage 即使是重啟瀏覽器進程后也會繼續有效, 直到用戶清除本地緩存. 

Blazor wasm 應用需要本地存儲的情形, 往往是用來保存  jwt 或 userId, 所以Local storage 更合適一些. session storage 相對雞肋一些, 完全可以使用 app state container 全局類代替, 所以不是本文關注的重點. 

Blazor wasm 使用Local storage的方法有:

=====================================

使用 blazored 的 LocalStorage

=====================================

 1. 安裝組件, 命令:  dotnet add package Blazored.LocalStorage

2. Program.cs 中注冊 LocalStorage 服務

3. _Imports.razor 文件中引用一下, 以方便頁面使用  @using Blazored.LocalStorage 

4. 需要存儲或讀取local storage的文件, 使用依賴注入的方式, 注入 ILocalStorageService 或 ISyncLocalStorageService 服務, 前者是異步版, 后者是同步版, 推薦使用異步版.

 

The APIs available are:

  • asynchronous via ILocalStorageService:

    • SetItemAsync()
    • SetItemAsStringAsync()
    • GetItemAsync()
    • GetItemAsStringAsync()
    • RemoveItemAsync()
    • ClearAsync()
    • LengthAsync()
    • KeyAsync()
    • ContainKeyAsync()
  • synchronous via ISyncLocalStorageService (Synchronous methods are only available in Blazor WebAssembly):

    • SetItem()
    • SetItemAsString()
    • GetItem()
    • GetItemAsString()
    • RemoveItem()
    • Clear()
    • Length()
    • Key()
    • ContainKey()

Note: Blazored.LocalStorage methods will handle the serialisation and de-serialisation of the data for you, the exceptions are the SetItemAsString[Async] and GetItemAsString[Async] methods which will save and return raw string values from local storage.

 

示例代碼:

@page "/"
@inject ILocalStorageService LocalStorageService
@inject ISyncLocalStorageService SyncLocalStorageService
<h1>Hello, world!</h1>

Welcome to your new app.
<br/>
<p>jwt:@Jwt</p>
<button class="btn btn-primary"  @onclick="SaveJwt"> Save Jwt</button>
<SurveyPrompt Title="How is Blazor working for you?" />

@code{ 
    private String Jwt;
    protected override void OnInitialized()
    {
        base.OnInitialized();
        ReadJwt();
    }

    private void ReadJwt()
    {
        Jwt = SyncLocalStorageService.GetItem<String>("jwt");
    }

    private void SaveJwt()
    {
        SyncLocalStorageService.SetItem<String>("jwt", "jwt123");
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM