Когда ReturnUrl -страница назначения- имеет атрибут Authorize и выполняется GetAuthenticationStateAsync(), protectedLocalStorage становится нулевым после NavigationManager.NavigateTo() выполняется.
Это соответствующий код для страницы входа
Код: Выделить всё
await protectedLocalStorage.SetAsync("authToken", token);
NavigationManager.NavigateTo(ReturnUrl ?? "");
Код: Выделить всё
ProtectedBrowserStorageResult result;
try
{
result = await protectedLocalStorage.GetAsync("authToken"); //protectedLocalStorage is null after the redirect
}
catch
{
result = new();
}
var anonymous = new ClaimsPrincipal(new ClaimsIdentity());
if (!result.Success) //Since protectedLocalStorage is null I get redirected back to login page.
{
return new AuthenticationState(anonymous);
}
Код: Выделить всё
@code {
[CascadingParameter] private HttpContext HttpContext { get; set; } = default!;
private IComponentRenderMode? RenderModeForPage => HttpContext.Request.Path.StartsWithSegments("/Account/Login") ? null : new InteractiveServerRenderMode(prerender: false);
//I added this because when login page's render mode is interactive server, it keeps reloading indefinitely
}
Код: Выделить всё
protected override void OnParametersSet()
{
if (HttpContext is null)
{
// If this code runs, we're currently rendering in interactive mode, so there is no HttpContext.
// The identity pages need to set cookies, so they require an HttpContext. To achieve this we
// must transition back from interactive mode to a server-rendered page.
NavigationManager.Refresh(forceReload: true);
}
}
Похоже, что функция NavigateTo() вызывает GetAuthenticationStateAsync() слишком рано в жизненном цикле Blazor, поэтому protectedLocalStorage еще не готов.
Я думаю, что проблема связана с режимом рендеринга страницы входа, поэтому как это сделать получить protectedLocalStorage правильно?
Подробнее здесь: https://stackoverflow.com/questions/792 ... er-login-u
Мобильная версия