在自定义的 Blazor 服务器端访问 AuthenticationStateProvider Class
Access AuthenticationStateProvider in Blazor Server Side in Custom Class
是否有关于如何在自定义 classes 中访问 Blazor 服务器端中的 AuthenticationStateProvider 的一般指导?是否应将 AuthenticationStateProvider 添加为单例服务?还有其他方法可以用 DI 获得它吗?我不是在谈论使用 AuthorizeViews 或通过级联参数。我需要能够在自定义 class 中获取 AuthenticationStateProvider.GetAuthenticationStateAsync(),而不是控制器、视图等
有什么想法吗?
感谢 Isaac 提供的信息,但实际上我能够回答我自己的问题。我的解决方案是确保我的助手 class 是有范围的而不是单例,以便获得 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;
是否有关于如何在自定义 classes 中访问 Blazor 服务器端中的 AuthenticationStateProvider 的一般指导?是否应将 AuthenticationStateProvider 添加为单例服务?还有其他方法可以用 DI 获得它吗?我不是在谈论使用 AuthorizeViews 或通过级联参数。我需要能够在自定义 class 中获取 AuthenticationStateProvider.GetAuthenticationStateAsync(),而不是控制器、视图等
有什么想法吗?
感谢 Isaac 提供的信息,但实际上我能够回答我自己的问题。我的解决方案是确保我的助手 class 是有范围的而不是单例,以便获得 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;