【问题标题】:Change the database in which ASP.NET Identity stores user data更改 ASP.NET Identity 存储用户数据的数据库
【发布时间】:2014-02-16 02:33:42
【问题描述】:

我们创建了一个新的 ASP.NET 4.5.1 项目,如下所示:

  • Visual Studio 2013
  • 新项目
  • Visual C#
  • 网络
  • ASP.NET Web 应用程序
  • Web API
  • 更改身份验证
  • 个人用户帐户
  • 好的>好的

在解决方案资源管理器 > App_Start > Startup.Auth.cs 文件中有以下代码配置 ASP.NET Indentity。我们如何更改 UserManager 存储用户数据的数据库?

static Startup()
{
    PublicClientId = "self";

    UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());

    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/Token"),
        Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
        AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        AllowInsecureHttp = true
    };
}

【问题讨论】:

  • UserStore 没有多个构造函数...
  • 没有一个 DbContext...
  • 是的。它也这样做。
  • 所以msdn.microsoft.com/en-us/library/gg679467(v=vs.113).aspx 或者我相信 UserStore 的默认构造函数会自行生成,使用“DefaultConnection”作为连接字符串名称。所以你可以在 web.config 中编辑它。

标签: c# asp.net asp.net-mvc asp.net-identity


【解决方案1】:

除了@ta.speot.is 和@Shaun 提到的内容:您还可以将上下文中的连接字符串的名称(存储在web.config 中)传递给IdentityDbContext 的base constructor

public class MyDbContext : IdentityDbContext<MyUser>
{
  public MyDbContext()
    : base("TheNameOfTheConnectionString")
  {
  }
}

tutorial 包含一个广泛的示例。

另一种方法是使用连接字符串的名称作为上下文构造函数的参数并将其传递给基本构造函数。

【讨论】:

  • 啊哈。所以你让 MyDbContext 继承 IdentityDbContext。这样做和继承普通的 DbContext 有什么区别?
  • IdentityDbContext 是 ASP.NET Identity 提供的上下文。它继承自DbContext,并为用户和角色管理添加了两个DbSet。如需更多信息,请查看this thread
  • 它不起作用,请你看看我的问题。谢谢。 stackoverflow.com/questions/21393195/…
【解决方案2】:

将您自己的DbContext 传递给UserStore 构造函数或更改名为DefaultConnection 的Web.config 连接字符串。无论哪种方式,@ta.speot.is 的 cmets 都是正确的。

正确

// do this - it's the factory pattern
UserManagerFactory 
= () => new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MyDbContext()));

不正确

// do NOT do this - use the preceding code. 
var userStore = new UserStore<IdentityUser>(new MyDbContext());                       
var userManager = new UserManager<IdentityUser>(userStore);
UserManagerFactory = () => userManager;

详情

UserStore 类公开了一个非常基本的用户管理 API。在代码中,我们将其配置为在MyDbContext 数据存储中以IdentityUser 类型存储用户数据。

UserManager 类公开了更高级别的用户管理 API,该 API 会自动保存对 UserStore 的更改。在代码中,我们将其配置为使用我们刚刚创建的UserStore

UserManagerFactory 应该实现工厂模式,以便为应用程序的每个请求获取一个 UserManager 实例。否则会出现以下异常:

模型在运行时不能使用上下文 正在创建。如果使用上下文,可能会抛出此异常 在 OnModelCreating 方法内,或者如果相同的上下文实例是 由多个线程同时访问。请注意,实例成员 DbContext 和相关类的不保证是线程的 安全。

就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多