dotnet / dotnet/aspnetcore

Blazor Identity and LocalStorage with InteractiveRenderMode

Open
#55,799 8 comments 0 reactions 0 assignees View on GitHub
area-blazor enhancement feature-blazor-server-auth
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

Ok, I am working on a Blazor Web App, including individual identity and local storage to build the cart. There is a `CartStateProvider` which provide realtime updates of the local storage for the whole app.

What I have learned from MS Document is the local storage required the render mode to be `InteractiveServerRenderMode(prerender: false)` which leads to another problem with the identity is that any page uses `AccountLayout` will stuck in reload loop because `HttpContext is null` while in `InteractiveServerRenderMode`.

What should we do in this scenario?

**App.razor**
```

```

**CartStateProvider**
```
@if (_isLoaded)
{

@ChildContent

}
else
{

}

@code {
private bool _isLoaded;

[Parameter]
public RenderFragment? ChildContent { get; set; }

public int TotalItems { get; set; }

protected override async Task OnInitializedAsync()
{
CartService.OnChange += Update;
TotalItems = await CartService.GetTotalItemsAsync();
_isLoaded = true;
}

private async void Update()
{
TotalItems = await CartService.GetTotalItemsAsync();
StateHasChanged();
}

public void Dispose()
{
CartService.OnChange -= StateHasChanged;
}
}
```

**CartService.cs**
```
public class CartService(ProtectedLocalStorage localStorage) : ICartService
{
private const string StorageKey = "cart";

public event Action? OnChange;

public async Task GetTotalItemsAsync()
{
var cartResult = await localStorage.GetAsync(StorageKey);
if (!cartResult.Success) return 0;
var cart = cartResult.Value;
return cart == null ? 0 : cart.Items.Sum(x => x.Quantity);
}
}
```

**Routes.razor**
```









```

There is a recommendation to add the dynamic render mode variable on `App.razor` but that won't work.

### Expected Behavior

_No response_

### Steps To Reproduce

_No response_

### Exceptions (if any)

_No response_

### .NET Version

8.0.205

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.