I apologize for what is probably a silly question, but I am a newbie to Blazor. Rather than adding authentication via the "Create Project" wizard, I am implementing my own.
I am running into an error calling into session storage in my async GetAuthenticationStateAsync method, when I initially load the site (from Visual Studio):
"InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendered. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method."
The error is easy to reproduce/simulate:
- Create a vanilla .NET Core 6 Blazor Server App using individual accounts.
- Navigate to the RevalidatingIdentityAuthenticationStateProvider class in Areas\Identity.
Replace the ctor and GetAuthenticateStateAsync with this:
private readonly ProtectedSessionStorage _sessionStorage;
public RevalidatingIdentityAuthenticationStateProvider(
ILoggerFactory loggerFactory,
IServiceScopeFactory scopeFactory,
IOptions<IdentityOptions> optionsAccessor,
ProtectedSessionStorage sessionStorage)
: base(loggerFactory)
{
_scopeFactory = scopeFactory;
_options = optionsAccessor.Value;
_sessionStorage = sessionStorage;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
// This will throw the error the first time it is called.
// My code does not call base, but will execute different logic based on whether
// the user is already logged in.
// This is merely to showcase the issue.
ProtectedBrowserStorageResult<bool> result = await _sessionStorage.GetAsync<bool>("username");
return base.GetAuthenticationStateAsync().Result;
}
I get the error, but not sure what the best way to workaround this is? The second time GetAuthenticationStateAsync() is called, calling _sessionStorage works just fine. Is there a check I can do to see if I can call _sessionStorage? Is there a better way to do this?
I based my code on a couple of examples that called _sessionStorage in GetAuthenticationStateAsync, which I am was a bit surprised that it no longer works. Howeber, the samples are working against older Blazor versions, so I am sure lots of things have changed.
Any help/pointers much appreciated.