gpt4 book ai didi

c# - 将身份资料保存在单独的数据库中

转载 作者:太空宇宙 更新时间:2023-11-03 13:00:01 25 4
gpt4 key购买 nike

我计划在全新的应用程序中实现 MVC 5.0 ASP.Net 标识。我引用了 Microsoft 文章 http://go.microsoft.com/fwlink/?LinkID=317594在身份表以外的单独表中添加客户资料信息。

但是根据我的要求,我想将客户资料信息存储在一个单独的数据库中,以便在数据库级别隔离用户身份信息和客户资料信息。身份在创建用户和个人资料信息时使用单一数据存储,而我需要为用户和个人资料信息设置两个不同的存储。有人对此有什么建议吗?

最佳答案

您可以简单地编写自定义 UserStore 类并扩展默认的 UserStore 类。考虑这个简单的例子:

public class ApplicationUser : IdentityUser
{
// other codes

// Add your extra profile information
// By Adding NotMapped attribute EF omits this and dose not puts in Identity's table
[NotMapped]
public Profile Profile { get; set; }
}

public class Profile
{
public int ID { get; set; }
public string ExtraData { get; set; }
// other properties
}

现在我们需要自定义用户存储来从 2 个数据库中放入和获取数据

public class MyUserStore : UserStore<ApplicationUser>
{
public MyUserStore(DbContext context)
: base(context)
{
// other implementation for second DB
}

public override Task CreateAsync(ApplicationUser user)
{
// save Profile object to separate DB
_mySecondDB.Save(User.Id, user.Profile);
return base.CreateAsync(user);
}

public override Task UpdateAsync(ApplicationUser user)
{
// same pattern as CreateAsync
}

public override Task DeleteAsync(ApplicationUser user)
{
// same pattern as CreateAsync
}


public override async Task<ApplicationUser> FindByIdAsync(string userId)
{
var user = await base.FindByIdAsync(userId);
user.Profile = _mySecondDB.FindProfileByUserId(userId);
return user;
}

public override Task<ApplicationUser> FindByNameAsync(string userName)
{
// same pattern as FindByIdAsync
}
}

现在您只需在身份管道中注入(inject)您的自定义用户存储。为此,请像这样更改 App_Start\IdentityConfig.cs 中的 ApplicationUserManager.Create 静态方法:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
var manager = new ApplicationUserManager(
new MyUserStore(context.Get<ApplicationDbContext>()));
// other codes
}

关于c# - 将身份资料保存在单独的数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32602788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com