.NET 6中在AuthenticationStateProvider使用Blazored.LocalStorage的构造函数问题
Blazor WebAssembly自定义AuthStateProvider依赖注入失败问题解决
问题场景
在Blazor WebAssembly项目中,尝试实现自定义CustomAuthStateProvider,通过注入ILocalStorageService读取本地存储的认证状态来构建AuthenticationState,但运行应用时触发错误:
无法找到BlazorBattles.Client.CustomAuthStateProvider的合适构造函数,需确保类型为具体类型且公共构造函数的所有参数已注册服务
移除构造函数和ILocalStorageService相关引用后程序可正常运行,添加后就会触发上述错误。
相关代码
CustomAuthStateProvider.cs
public class CustomAuthStateProvider : AuthenticationStateProvider { private readonly ILocalStorageService _localStorageService; CustomAuthStateProvider(ILocalStorageService localStorageService) { _localStorageService = localStorageService; } public override async Task<AuthenticationState> GetAuthenticationStateAsync() { if (await _localStorageService.GetItemAsync<bool>("isAuthenticated")) { ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "Thomas") }, "Test Authentication"); ClaimsPrincipal user = new ClaimsPrincipal(claimsIdentity); AuthenticationState state = new AuthenticationState(user); // 通知所有组件认证状态已变更 NotifyAuthenticationStateChanged(Task.FromResult(state)); return (state); } // 返回未授权用户(无ClaimsIdentity) return (new AuthenticationState(new ClaimsPrincipal())); } }
Program.cs
using BlazorBattles.Client; using BlazorBattles.Client.Services; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Blazored.Toast; using Blazored.LocalStorage; using Microsoft.AspNetCore.Components.Authorization; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("#app"); builder.RootComponents.Add<HeadOutlet>("head::after"); builder.Services.AddBlazoredToast(); builder.Services.AddBlazoredLocalStorage(); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddScoped<IBananaService, BananaService>(); builder.Services.AddScoped<IUnitService, UnitService>(); builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>(); builder.Services.AddOptions(); builder.Services.AddAuthorizationCore(); await builder.Build().RunAsync();
使用版本
- Blazored.LocalStorage V4.3.0
- Microsoft.AspNetCore.Components.Authorization V6
错误原因
CustomAuthStateProvider的构造函数未添加public修饰符,C#中类成员默认访问级别为private,导致依赖注入容器无法访问该构造函数来实例化对象并注入ILocalStorageService。
解决方案
为CustomAuthStateProvider的构造函数添加public关键字,让DI容器能够正常调用构造函数完成依赖注入:
public class CustomAuthStateProvider : AuthenticationStateProvider { private readonly ILocalStorageService _localStorageService; // 添加public修饰符 public CustomAuthStateProvider(ILocalStorageService localStorageService) { _localStorageService = localStorageService; } // 其余代码保持不变... }
内容的提问来源于stack exchange,提问作者ThomasRogers
相关产品推荐
相关产品推荐

