当使用AspNetCore Identity时,你可以通过继承IdentityUser
类来为用户添加自定义属性。以下是一种解决方法的代码示例:
IdentityUser
的自定义用户类ApplicationUser
,并在其中添加你需要的自定义属性。using Microsoft.AspNetCore.Identity;
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
// 添加其他自定义属性
}
Startup.cs
文件中的ConfigureServices
方法中,将IdentityUser
替换为ApplicationUser
。public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
// ...
}
DbContext
类(通常是ApplicationDbContext
)中,将IdentityUser
替换为ApplicationUser
。using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : IdentityDbContext
{
// ...
}
现在,你可以使用ApplicationUser
类来访问自定义的属性了。例如:
public class SomeController : Controller
{
private readonly UserManager _userManager;
public SomeController(UserManager userManager)
{
_userManager = userManager;
}
public async Task SomeAction()
{
var userId = User.GetUserId();
var user = await _userManager.FindByIdAsync(userId);
var firstName = user.FirstName;
var lastName = user.LastName;
// ...
return View();
}
}
以上示例中,ApplicationUser
类添加了FirstName
和LastName
属性,并且在SomeController
中使用UserManager
来获取当前用户的信息,并访问自定义属性。