Skip to content

Basic Use

Oscar Soto edited this page Dec 2, 2025 · 1 revision

Storing, Retrieving, and Deleting the Session

The following CRUD operations are performed through the ISessionProvider service, so it will need to be injected into the page where you plan to manage sessions:

@inject ISessionProvider _provider

Creating the Session

In the section where the user's session will be generated, you must create the corresponding session in the application.
The following example uses the default settings when installing BSP in a Blazor Server application.

@page "/login"
@inject ISessionProvider _provider
@inject DatabaseService _db
@inject NavigationManager Nav

...
@* Form here *@
...

@code
{
	public async Task Login(string user, string pass)
	{
		// Validate the user
		if (!_db.IsValidUser(user, pass))
			return "User or password incorrect!";
		var user = _db.GetUser(user);
		
		// ✅ Create the user's session
		await _provider.CreateNewSession("user", user);
		Nav.NavigateTo("/");
		
		// Or, you can make it empty at the beginning
		await _provider.CreateNewSession();
		Nav.NavigateTo("/");
	}
}

This generates a new session ID for the user in cookies, and a session state in the application, ready to manage the user's information.

CRUD Methods

The following methods allow you to perform CRUD operations on the user's session.

Important
The methods shown can be executed when initializing a component/page. This is only possible starting from version 1.1.0.
For version 1.0.4 or lower, by default, access is only possible from the OnAfterRender method.

Add Session (CREATE & UPDATE)

You can add a session value using the following function:

await _provider.SetSession("key value", "value");

You can use the same function to overwrite the key's value.

Example
@page "/home"
@inject ISessionProvider _provider

...

@code
{
	protected override async Task OnInitializedAsync()
	{
		await _provider.SetSession("value", 0);
	}
	
	protected override async Task OnAfterRenderAsync(bool firstRender)
	{
		if (!firstRender)
			await _provider.SetSession("value", 1);
	}
	
	...
}

Get Session (READ & DELETE)

You can retrieve the session value using the following method.
You must specify the type of the value you want to return.

int value = await _provider.GetSession<int>("key value");

To delete the session value, simply add true at the end of the parameters:

_ = await _provider.GetSession<int>("key value", true);
Example
@page "/home"
@inject ISessionProvider _provider

...

@code
{
	async Task RandomFunction()
	{
		string name = await _provider.GetSession("userName");
		/* DO something ... */
	}
}

Removing the Session

When logging out a user, their corresponding entry in the dictionary (keeper) must be destroyed:

await _provider.RemoveSession();

Clone this wiki locally