防止 ASP.NET Identity 的 UserManager 自动保存

问题描述 投票:0回答:2

我正在尝试与 ASP.NET Identity 及其 UserManager 集成。我有自己的自定义用户对象,已将其添加到开箱即用的 ApplicationUser 中。 UserManager 有一个 Create() 方法(实际上它位于 UserManagerExtensions 类中),用于创建新用户。问题是它会自动将更改保存到数据库中,并在here确认。我想在保存新用户之前在同一“事务”中执行一些其他操作,这样我就无法让 UserManager 自动保存更改。

有趣的是,我重写了与 UserManager 关联的 DbContext 中的 SaveChange() 方法,但它永远不会中断该方法以在 Create() 中自动保存。

有什么方法可以配置 UserManager 不自动保存更改。

c# asp.net asp.net-identity asp.net-identity-2
2个回答
8
投票

此功能已默认实现

UserStore
。因此你只需要配置它。在
ApplicationUserManager.Create()
静态方法中,或在实例化
UserStore
的任何地方,将
AutoSaveChanges
设置为
false

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
    var manager = new ApplicationUserManager(
        new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()) 
             { AutoSaveChanges = false });

    // rest of codes
}

0
投票

在 .net core 6 中这是如何完成的?

© www.soinside.com 2019 - 2024. All rights reserved.