dependency-injection - 如何在 Blazor 类中注入服务(AuthenticationStateProvider)
问题描述
我正在努力在 Blazor 服务器的类中注入服务 (AuthenticationStateProvider)。如果我在剃须刀组件中执行此操作,则非常简单:
@inject AuthenticationStateProvider AuthenticationStateProvider
接着
private async Task LogUsername()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
ClientMachineName = $"{user.Identity.Name}";
}
else
{
ClientMachineName = "Unknown";
}
}
但是我需要这样做,即在类而不是剃刀组件中检索经过身份验证的用户机器名称。
我试过例如:
[Inject]
AuthenticationStateProvider AuthenticationStateProvider { get; set; }
public async Task LogUsername()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
ClientMachineName = $"{user.Identity.Name}";
}
else
{
ClientMachineName = "Unknown";
}
}
但这似乎不起作用。
任何帮助将非常感激。
解决方案
使用 Blazor 服务器(.Net Core 3),这对我有用:
public class AuthTest
{
private readonly AuthenticationStateProvider _authenticationStateProvider;
public AuthTest(AuthenticationStateProvider authenticationStateProvider)
{
_authenticationStateProvider = authenticationStateProvider;
}
public async Task<IIdentity> GetIdentity()
{
var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
return user.Identity;
}
}
您需要在 ASP.Net Core DI 中注册Startup.ConfigureServices
:
services.AddScoped<AuthTest>();
然后将其注入您的.razor
页面:
@page "/AuthTest"
@inject AuthTest authTest;
<button @onclick="@LogUsername">Write user info to console</button>
@code{
private async Task LogUsername()
{
var identity= await authTest.IsAuthenticated();
Console.WriteLine(identity.Name);
}
您应该看到写入 ASP.Net 输出控制台的登录用户名。
更新如果您想从一个单独的类中获取当前登录的用户并且您没有将其注入到 blazor 页面,请按照此处的指导进行操作
推荐阅读
- javascript - React Redux - 不变量失败:在调度中检测到状态突变
- spring - 我可以将 application.properties 文件添加到 Spring Boot 项目吗?
- filter - Powerbi groupby 过滤器,用于在包含特定值时看不到数据
- android - Junit 4 在 kotlin 中测试内部类
- flutter - 颤动中可调整大小的拼贴视图
- mysql - MySql:如何使用多个枢轴连接这两个表
- r - 如何从R中的数据集中删除浮动值
- javascript - 使用数组长度创建重复对象
- sql - Sql - 使用连接从大表(100M+)中获取记录时查询慢,提示?
- html - 动画 - 如何选择动画完成时发生的事情