使用.NET 10的 Blazor Server应用需要实现与.NET 4.8的 Membership(System.Web.Security)等价的功能
我正在把一个非常老的.NET 4.8框架的ASP.NET Web Forms应用(包含 .aspx 页)迁移到在.NET 10上的Blazor Server。
我似乎找不到在 System.Web.Security 中的等效流程,在其中我需要有Membership类及相关的支持,例如:
var aUser = Membership.GetUser(userName)
user.ResetPassword()
Membership.UpdateUser()
Membership.DeleteUser()
Blazor/Razor页面
@using Microsoft.AspNetCore.Identity
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject UserManager<IdentityUser> UserManager
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity != null && user.Identity.IsAuthenticated)
{
if (user.Identity.Name != null)
{
var currentUser = await UserManager.FindByNameAsync(user.Identity.Name);
}
}
这会在运行时触发以下错误:
未注册的类型为 'Microsoft.AspNetCore.Identity.UserManager' 的服务
在 program.cs 中,我尝试注册该服务:
builder.Services.AddIdentity()
.AddEntityFrameworkStores<ApplicationDbContext>();
但这不是有效的语法,我怎么也找不到正确的语法是什么?
也许在.NET 10 Blazor Server中没有Membership的等效实现?
欢迎任何帮助。
解决方案
提问中的代码使用了错误的类型。在一个新的Blazor项目中无法复现这个问题。注册的用户类型是 ApplicationUser,而不是 IdentityUser。默认的项目模板使用 ApplicationUser。
当使用内置模板创建一个新的Blazor Server项目时,可以使用 -au 参数来添加单独身份验证(Individual authentication):
dotnet new blazor -au Individual -f net10.0
这在 dotnet run 下就能运行。我不指定Server interactivity模式,因为它是默认值。
这会创建一个使用SQLite作为用户后端存储的新项目。Program.cs顶部的代码设置了身份验证:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();
...
位于 Components\Account\Pages 文件夹中的页面可以无问题地导入Identity服务。例如 Register.razor 页面以以下内容开头:
@using System.ComponentModel.DataAnnotations
@using System.Text
@using System.Text.Encodings.Web
@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.WebUtilities
@using blaz_server_auth.Data
@inject UserManager<ApplicationUser> UserManager
@inject IUserStore<ApplicationUser> UserStore
@inject SignInManager<ApplicationUser> SignInManager
...
并且在后面的
public async Task RegisterUser(EditContext editContext)
{
var user = CreateUser();
await UserStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
var emailStore = GetEmailStore();
await emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
var result = await UserManager.CreateAsync(user, Input.Password);
...
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。