gpt4 book ai didi

dependency-injection - 如何在 Blazor 类中注入(inject)服务(AuthenticationStateProvider)

转载 作者:行者123 更新时间:2023-12-03 16:37:43 25 4
gpt4 key购买 nike

我正在努力在 Blazor 服务器的类中注入(inject)服务 (AuthenticationStateProvider)。如果我在 Razor 组件中执行此操作,则非常简单:
@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";
}
}

但是我需要这样做,即在类而不是 Razor 组件中检索经过身份验证的用户机器名称。

我试过例如:
[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;
}
}
您需要在 Startup.ConfigureServices 中向 ASP.Net Core DI 注册它。 :
services.AddScoped<AuthTest>();
然后将其注入(inject)您的 .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 输出控制台的登录用户名。
更新
如果您想从一个单独的类中获取当前登录的用户并且您没有将其注入(inject)到 blazor 页面中,请遵循指南 here

关于dependency-injection - 如何在 Blazor 类中注入(inject)服务(AuthenticationStateProvider),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59736931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com