Like the title says, I am wondering how to save strings to session storage in Blazor Server in the _Host.cshtml file to then read them in the other Blazor pages. I am getting data from a LiteDB database. I tries using the Blazored.SessionStorage package, but I got an error, without a direct code?, it just redirected me. This happens when I try to do the right way of putting the await before the line.
SessionStorage.SetItemAsync("Title", (homepageObj != null) ? "Working" : "Working");
This is the code I try to do so it doen’t give me an error. But the problem is, when I try to then read the data just below the saving, it returns as empty. Code for reading the session:
var val = SessionStorage.GetItemAsStringAsync("Title");
>Solution :
You can use Session object to store and retrive data from session storage.Try the following code to save the string in the session storage from the _Host.cshtml page.
Example:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
HttpContextAccessor.HttpContext.Session.SetString("Title", (homepageObj != null) ? "Working" : "Not Working");
}
To read the data from other blazor pages use the same HttpContextAccessor to access the session data.
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@code {
private string title;
protected override void OnInitialized()
{
title = HttpContextAccessor.HttpContext.Session.GetString("Title");
}
}