我已经在我的 Blazor 服务器项目中实现了此类(使用 .net 6.0)。
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
public CustomAuthenticationStateProvider(ProtectedSessionStorage sessionStorage)
{
_sessionStorage = sessionStorage;
}
// also contains working code which isn't relevant to this problem (so not shown for brevity).
}
DI 启动代码如下所示:
builder.Services.AddAuthenticationCore();
builder.Services.AddRazorPages();
builder.Services.AddScoped<ProtectedSessionStorage>();
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
但是,当尝试从登录页面(剃刀组件)访问它时,找不到
CustomAuthenticationStateProvider
。
标记(仅限相关行):
@inject AuthenticationStateProvider authStateProvider
<div class="button login" @onclick="() => DoLogin()">
Login
</div>
标记错误的方法:
private async Task DoLogin()
{
var customAuthStateProvider = authStateProvider as CustomAuthenticationStateProvider;
await customAuthStateProvider.UpdateAuthenticationState(new UserSession
{
UserName = _inputUsername,
Role = "admin"
});
}
但是,
customAuthStateProvider
始终为空,因为authStateProvider
(注入到剃刀组件中)不是CustomAuthenticationStateProvider
的作用域实例...它只是AuthenticationStateProvider
的其他实例。
没有足够的声誉来发表评论,但希望这会有所帮助。 您应该注入 CustomAuthenticationStateProvider,而不是 AuthenticationStateProvider。
@inject CustomAuthenticationStateProvider authStateProvider
然后它应该可以访问。 您可能还必须将身份验证添加到program.cs。你的“AddAuthenticationCore”可能会做同样的事情,我不太熟悉。
app.UseAuthentication();
我还添加了有点不同的身份验证提供程序(“AuthenticationProvider”),也许值得一试。
builder.Services.AddScoped<AuthenticationProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(sp => sp.GetRequiredService<AuthenticationProvider>());