-
Notifications
You must be signed in to change notification settings - Fork 0
Basic Use
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 _providerIn 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.
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 theOnAfterRendermethod.
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.
@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);
}
...
}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);@page "/home"
@inject ISessionProvider _provider
...
@code
{
async Task RandomFunction()
{
string name = await _provider.GetSession("userName");
/* DO something ... */
}
}When logging out a user, their corresponding entry in the dictionary (keeper) must be destroyed:
await _provider.RemoveSession();Made with ❤️ by Oscar D. Soto