问题出在自定义 AuthenticationStateProvider 中 GetAuthenticationStateAsync 方法在服务端调用时并不能正确获取用户的身份信息。解决方案如下:
1.设置 App.razor 中的组件为 AuthorizeRouteView,并将 AuthenticationStateProvider 属性设置为自定义的 CustomAuthenticationStateProvider。
You are not authorized to access this resource. Sorry, there's nothing at this address.
2.在注入服务中使用 AddScoped
services.AddScoped
3.在自定义的 AuthenticationStateProvider 中重写 GetAuthenticationStateAsync 方法,并在客户端和服务器端分别处理身份验证状态,如下代码:
public async override Task
return new AuthenticationState(new ClaimsPrincipal(identity));
}
4.在服务器端 Blazor 页面中重写 OnInitializedAsync 方法并调用 GetAuthenticationStateAsync 方法,确保身份验证信息能够正确传递。
protected override async Task OnInitializedAsync() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; // ... }
这些步骤应该能够解决自定义 AuthenticationStateProvider 在 Blazor 服务器端中无法正确工作的问题