我将以下自定义登录添加到默认Blazor应用程序模板的index.razor中(无需身份验证(。
<form>
<button @onclick="SignIn">Sign in</button>
</form>
@inject AuthenticationStateProvider AuthenticationStateProvider
@code {
private string userName = "FakeUser";
private async Task SignIn(MouseEventArgs e)
{
var fakeUser = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, userName),
}, "Fake authentication type"));
var provider = (IHostEnvironmentAuthenticationStateProvider)AuthenticationStateProvider;
//provider is ServerAuthenticationStateProvider
provider.SetAuthenticationState(Task.FromResult(new AuthenticationState(fakeUser)));
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
//authState.User.Identity.Name == "Fake User" - this is ok
}
}
然而,当我导航到另一个页面时,authState并没有持久化:
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
//authState.User.Identity.Name == null ??
}
为什么?
我运行了您的代码,它确实保持了身份验证状态。。。
这是我的代码:
索引.razor
@page "/"
@using System.Security.Claims;
<button @onclick="SignIn">Sign in</button>
@inject AuthenticationStateProvider AuthenticationStateProvider
@code {
private string userName = "FakeUser";
private async Task SignIn(MouseEventArgs e)
{
var fakeUser = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, userName),
}, "Fake authentication type"));
var provider =
(IHostEnvironmentAuthenticationStateProvider)AuthenticationStateProvider;
//provider is ServerAuthenticationStateProvider
provider.SetAuthenticationState(Task.FromResult(new
AuthenticationState(fakeUser)));
var authState = await
AuthenticationStateProvider.GetAuthenticationStateAsync();
Console.WriteLine(authState.User.Identity.Name);
}
}
计数器.razor
@page "/counter"
@inject AuthenticationStateProvider AuthenticationStateProvider
@code {
protected override async Task OnInitializedAsync()
{
var authState = await
AuthenticationStateProvider.GetAuthenticationStateAsync();
Console.WriteLine(authState.User.Identity.Name);
}
}
请运行您的应用程序,单击按钮元素,然后按导航菜单中的"计数器"菜单项导航到计数器组件。。。现在转到"输出"窗口,查看单词FakeUser是否打印了两次。
问题是,<button>
在本机<form>
元素中,因为它提交了表单(重新加载页面(
<form>
<button @onclick="SignIn">Sign in</button>
</form>
解决方案:
请使用<EditForm>或
<button type="button" @onclick="SignIn">Sign in</button>