Blazored.LocalStorage 4.5.0

Prefix Reserved
dotnet add package Blazored.LocalStorage --version 4.5.0
                    
NuGet\Install-Package Blazored.LocalStorage -Version 4.5.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Blazored.LocalStorage" Version="4.5.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Blazored.LocalStorage" Version="4.5.0" />
                    
Directory.Packages.props
<PackageReference Include="Blazored.LocalStorage" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Blazored.LocalStorage --version 4.5.0
                    
#r "nuget: Blazored.LocalStorage, 4.5.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Blazored.LocalStorage&version=4.5.0
                    
Install Blazored.LocalStorage as a Cake Addin
#tool nuget:?package=Blazored.LocalStorage&version=4.5.0
                    
Install Blazored.LocalStorage as a Cake Tool

Nuget version Nuget downloads Build & Test Main

Blazored LocalStorage

Blazored LocalStorage is a library that provides access to the browsers local storage APIs for Blazor applications. An additional benefit of using this library is that it will handle serializing and deserializing values when saving or retrieving them.

Breaking Changes (v3 > v4)

JsonSerializerOptions

From v4 onwards we use the default the JsonSerializerOptions for System.Text.Json instead of using custom ones. This will cause values saved to local storage with v3 to break things. To retain the old settings use the following configuration when adding Blazored LocalStorage to the DI container:

builder.Services.AddBlazoredLocalStorage(config =>
{
    config.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
    config.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    config.JsonSerializerOptions.IgnoreReadOnlyProperties = true;
    config.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
    config.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    config.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;
    config.JsonSerializerOptions.WriteIndented = false;
});

SetItem[Async] method now serializes string values

Prior to v4 we bypassed the serialization of string values as it seemed a pointless as string can be stored directly. However, this led to some edge cases where nullable strings were being saved as the string "null". Then when retrieved, instead of being null the value was "null". By serializing strings this issue is taken care of. For those who wish to save raw string values, a new method SetValueAsString[Async] is available. This will save a string value without attempting to serialize it and will throw an exception if a null string is attempted to be saved.

Installing

To install the package add the following line to you csproj file replacing x.x.x with the latest version number (found at the top of this file):

<PackageReference Include="Blazored.LocalStorage" Version="x.x.x" />

You can also install via the .NET CLI with the following command:

dotnet add package Blazored.LocalStorage

If you're using Visual Studio you can also install via the built in NuGet package manager.

Setup

You will need to register the local storage services with the service collection in your Startup.cs file in Blazor Server.

public void ConfigureServices(IServiceCollection services)
{
    services.AddBlazoredLocalStorage();
}

Or in your Program.cs file in Blazor WebAssembly.

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("app");

    builder.Services.AddBlazoredLocalStorage();

    await builder.Build().RunAsync();
}

Registering services as Singleton - Blazor WebAssembly ONLY

99% of developers will want to register Blazored LocalStorage using the method described above. However, in some very specific scenarios developer may have a need to register services as Singleton as apposed to Scoped. This is possible by using the following method:

builder.Services.AddBlazoredLocalStorageAsSingleton();

This method will not work with Blazor Server applications as Blazor's JS interop services are registered as Scoped and cannot be injected into Singletons.

Usage (Blazor WebAssembly)

To use Blazored.LocalStorage in Blazor WebAssembly, inject the ILocalStorageService per the example below.

@inject Blazored.LocalStorage.ILocalStorageService localStorage

@code {

    protected override async Task OnInitializedAsync()
    {
        await localStorage.SetItemAsync("name", "John Smith");
        var name = await localStorage.GetItemAsync<string>("name");
    }

}

With Blazor WebAssembly you also have the option of a synchronous API, if your use case requires it. You can swap the ILocalStorageService for ISyncLocalStorageService which allows you to avoid use of async/await. For either interface, the method names are the same.

@inject Blazored.LocalStorage.ISyncLocalStorageService localStorage

@code {

    protected override void OnInitialized()
    {
        localStorage.SetItem("name", "John Smith");
        var name = localStorage.GetItem<string>("name");
    }

}

Usage (Blazor Server)

NOTE: Due to pre-rendering in Blazor Server you can't perform any JS interop until the OnAfterRender lifecycle method.

@inject Blazored.LocalStorage.ILocalStorageService localStorage

@code {

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await localStorage.SetItemAsync("name", "John Smith");
        var name = await localStorage.GetItemAsync<string>("name");
    }

}

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.

Configuring JSON Serializer Options

You can configure the options for the default serializer (System.Text.Json) when calling the AddBlazoredLocalStorage method to register services.

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("app");

    builder.Services.AddBlazoredLocalStorage(config =>
        config.JsonSerializerOptions.WriteIndented = true
    );

    await builder.Build().RunAsync();
}

Using a custom JSON serializer

By default, the library uses System.Text.Json. If you prefer to use a different JSON library for serialization--or if you want to add some custom logic when serializing or deserializing--you can provide your own serializer which implements the Blazored.LocalStorage.Serialization.IJsonSerializer interface.

To register your own serializer in place of the default one, you can do the following:

builder.Services.AddBlazoredLocalStorage();
builder.Services.Replace(ServiceDescriptor.Scoped<IJsonSerializer, MySerializer>());

You can find an example of this in the Blazor Server sample project. The standard serializer has been replaced with a new serializer which uses NewtonsoftJson.

Testing with bUnit

The Blazored.LocalStorage.TestExtensions package provides test extensions for use with the bUnit testing library. Using these test extensions will provide an in memory implementation which mimics local storage allowing more realistic testing of your components.

Installing

To install the package add the following line to you csproj file replacing x.x.x with the latest version number (found at the top of this file):

<PackageReference Include="Blazored.LocalStorage.TestExtensions" Version="x.x.x" />

You can also install via the .NET CLI with the following command:

dotnet add package Blazored.LocalStorage.TestExtensions

If you're using Visual Studio you can also install via the built in NuGet package manager.

Usage example

Below is an example test which uses these extensions. You can find an example project which shows this code in action in the samples folder.

public class IndexPageTests : TestContext
{
    [Fact]
    public async Task SavesNameToLocalStorage()
    {
        // Arrange
        const string inputName = "John Smith";
        var localStorage = this.AddBlazoredLocalStorage();
        var cut = RenderComponent<BlazorWebAssembly.Pages.Index>();

        // Act
        cut.Find("#Name").Change(inputName);
        cut.Find("#NameButton").Click();
            
        // Assert
        var name = await localStorage.GetItemAsync<string>("name");
            
        Assert.Equal(inputName, name);
    }
}
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (174)

Showing the top 5 NuGet packages that depend on Blazored.LocalStorage:

Package Downloads
Blazored.LocalStorage.TestExtensions

A testing library to provide helper extensions for Blazored.LocalStorage

Blauhaus.MVVM.Blazor

Package Description

RapidCMS.UI

RapidCMS is a Blazor framework which allows you to build a responsive and flexible CMS purely from code.

Elsa.Studio.Core

Core Elsa Studio services.

Elsa.Studio.Shared

Elsa Studio shared services and components.

GitHub repositories (45)

Showing the top 20 popular GitHub repositories that depend on Blazored.LocalStorage:

Repository Stars
dotnet-architecture/eShopOnWeb
Sample ASP.NET Core 8.0 reference application, now community supported: https://github.com/NimblePros/eShopOnWeb
MudBlazor/MudBlazor
Blazor Component Library based on Material Design principles with an emphasis on ease of use and extensibility
fullstackhero/dotnet-starter-kit
Production Grade Cloud-Ready .NET 9 Starter Kit (Web API + Blazor Client) with Multitenancy Support, and Clean/Modular Architecture that saves roughly 200+ Development Hours! All Batteries Included.
fullstackhero/blazor-starter-kit
Clean Architecture Template for Blazor WebAssembly Built with MudBlazor Components.
Megabit/Blazorise
Blazorise is a component library built on top of Blazor with support for CSS frameworks like Bootstrap, Tailwind, Bulma, AntDesign, and Material.
Webreaper/Damselfly
Damselfly is a server-based Photograph Management app. The goal of Damselfly is to index an extremely large collection of images, and allow easy search and retrieval of those images, using metadata such as the IPTC keyword tags, as well as the folder and file names. Damselfly includes support for object/face detection.
WebVella/WebVella-ERP
Free and open-source pluggable ERP and CRM software based on ASP.NET Core 9, RazorPages and PostgreSQL . Targets Linux or Windows as host OS.
json-everything/json-everything
System.Text.Json-based support for all of your JSON needs.
Yu-Core/SwashbucklerDiary
侠客日记是一个开源、跨平台的本地日记app,使用Blazor开发,支持Android,Windows,macOS,Web,Linux。"SwashbucklerDiary" is an open source cross-platform local diary app using Blazor , support Android,Windows,macOS,Web,Linux.
DragoQCC/CrucibleC2
A C# Command & Control framework
csharpfritz/csharp_with_csharpfritz
Show notes, slides, and samples from the CSharp with CSharpFritz show
TimeWarpEngineering/timewarp-state
A Blazor State management library by TimeWarp.
lanedirt/AliasVault
A self-hostable, end-to-end encrypted password manager with a built-in alias generator and email server.
supabase-community/supabase-csharp
A C# Client library for Supabase
fullstackhero/blazor-wasm-boilerplate
Clean Architecture Boilerplate Template for .NET 6.0 Blazor WebAssembly built for FSH WebAPI with the goodness of MudBlazor Components.
CuriousDrive/BlazingChat
BlazingChat is a Blazor WebAssembly app developed by CuriousDrive for the community. This is a sample application for developers who are just getting started with Blazor.
TanvirArjel/CleanArchitecture
This repository contains the implementation of domain-driven design and clear architecture in ASP.NET Core.
neozhu/visitormanagement
helps in managing visitors visiting the institutions for various reasons. It allows visitors to check-in digitally to eliminate the tedious registeration and other paperwork. Additionally, it also keeps a track of every individual inside the campus and their timings. Institutions has guards who enter their detail in some notebooks to keep a log which are practically impossible to reconcile. It is really unpleasent and hectic for visitor to stand at the gate and give details about the visit. To ease the process of registeration, Entry-In, Entry-Out, time tracking and logging the history, this VMS can be of great use!!
dashiell-zhang/NetEngine
基于 .Net 框架搭建的一个基础项目结构
ThomasBleijendaal/RapidCMS
RapidCMS is a Blazor framework which allows you to build a responsive and flexible CMS purely from code. It provides a basic set of editors and controls, and is fully customisable.
Version Downloads Last updated
4.5.0 3,323,352 2/10/2024
4.4.0 1,597,230 8/14/2023
4.3.0 2,358,562 11/9/2022
4.3.0-preview.1 132,955 3/28/2022
4.2.0 2,306,038 2/4/2022
4.1.5 957,944 8/21/2021
4.1.4 1,945 8/21/2021
4.1.2 249,886 6/13/2021
4.1.1 87,676 5/15/2021
4.0.0 29,728 5/8/2021
3.0.0 856,651 7/23/2020
2.2.0 8,950 7/23/2020
2.1.6 140,950 5/21/2020
2.1.5 70,343 3/31/2020
2.1.4 2,047 3/30/2020
2.1.3 4,298 3/27/2020
2.1.1 135,943 9/25/2019
2.1.0 3,203 9/19/2019
2.0.14 664 9/17/2019
2.0.13 1,145 9/5/2019
2.0.12 2,879 8/19/2019
2.0.11 950 8/14/2019
2.0.10 466 8/14/2019
2.0.9 432 8/14/2019
2.0.8 455 8/13/2019
2.0.7 1,071 7/27/2019
2.0.6 458 7/25/2019
2.0.5 456 7/25/2019
2.0.3 422 7/25/2019
2.0.2 1,262 6/13/2019
2.0.1 2,127 5/31/2019
2.0.0 3,313 4/19/2019
1.2.1 2,321 3/15/2019
1.2.0 1,955 3/13/2019
1.1.0 1,983 3/9/2019
1.0.4 1,868 3/9/2019
1.0.3 1,929 3/4/2019
1.0.2 1,862 3/2/2019
1.0.1 2,151 2/9/2019
1.0.0 2,248 1/30/2019