【问题标题】:Access AuthenticationStateProvider in Blazor Server Side in Custom Class在自定义类中访问 Blazor 服务器端的 AuthenticationStateProvider
【发布时间】:2020-03-25 20:10:14
【问题描述】:

是否有关于如何在自定义类中访问 Blazor 服务器端的 AuthenticationStateProvider 的一般指导? AuthenticationStateProvider 是否应该作为单例服务添加?还有其他方法可以使用 DI 吗?我不是在谈论使用 AuthorizeViews 或通过级联参数。我需要能够在自定义类中获取 AuthenticationStateProvider.GetAuthenticationStateAsync(),而不是控制器、视图等。

有什么想法吗?

【问题讨论】:

    标签: asp.net-core blazor blazor-server-side


    【解决方案1】:

    感谢 Isaac 提供的信息,但我实际上能够回答我自己的问题。我的解决方案是确保我的助手类是作用域的,而不是单例的,以便获取 authstateprovider 的实例。

    services.AddScoped<Classes.GlobalHelper>();
    

    然后我可以像任何其他 DI 一样调用 authstateprovider,例如:

    public async Task<HttpClient> MyHttpClient()
    {
        AuthenticationState _authstate = _authStateProv.GetAuthenticationStateAsync().Result;
    
        HttpClient http = new HttpClient();
        string signedInUserID = _authstate.User.FindFirst(ClaimTypes.NameIdentifier).Value;
    

    【讨论】:

    • 为什么叫 Result ?您应该等待对 GetAuthenticationStateAsync 的调用。调用 Result 错误并阻塞。
    • 在我完成之前粘贴了代码……是的……等待中。
    • 有兴趣回答上述问题的人:stackoverflow.com/a/62529030/6152891
    猜你喜欢
    • 2021-11-29
    • 2020-03-19
    • 2020-05-01
    • 2020-10-13
    • 2019-05-17
    • 2020-06-22
    • 1970-01-01
    • 2020-09-02
    • 2020-03-20
    相关资源
    最近更新 更多