首页 > 解决方案 > 如何在 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";
    }
}

但这似乎不起作用。

任何帮助将非常感激。

标签: dependency-injectionblazorblazor-server-side

解决方案


使用 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 页面,请按照此处的指导进行操作


推荐阅读