Sha*_*tin 14 c# asp.net asp.net-mvc asp.net-identity
我们创建了一个新的ASP.NET 4.5.1项目,如下所示:
在解决方案资源管理器> 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
};
}
Run Code Online (Sandbox Code Playgroud)
除了@ ta.speot.is和@Shaun提到的内容之外:您还可以将上下文中的连接字符串(存储在web.config中)的名称传递给IdentityDbContext 的基础构造函数
public class MyDbContext : IdentityDbContext<MyUser>
{
public MyDbContext()
: base("TheNameOfTheConnectionString")
{
}
}
Run Code Online (Sandbox Code Playgroud)
本教程包含一个广泛的示例.
另一种方法是使用连接字符串的名称作为上下文构造函数的参数,并将其传递给基础构造函数.
将您自己的代码传递DbContext
给UserStore
构造函数或更改名为的Web.config连接字符串DefaultConnection
.无论哪种方式,@ ta.speot.is的评论都是正确的.
正确
// do this - it's the factory pattern
UserManagerFactory
= () => new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MyDbContext()));
Run Code Online (Sandbox Code Playgroud)
不正确
// do NOT do this - use the preceding code.
var userStore = new UserStore<IdentityUser>(new MyDbContext());
var userManager = new UserManager<IdentityUser>(userStore);
UserManagerFactory = () => userManager;
Run Code Online (Sandbox Code Playgroud)
细节
本UserStore
类暴露了一个非常基本的用户管理API.在代码中,我们将其配置为用户存储数据类型IdentityUser
的MyDbContext
数据存储.
本UserManager
类暴露了一个更高层次的用户管理API,它会自动保存更改UserStore
.在代码中,我们将其配置为使用UserStore
我们刚刚创建的.
本UserManagerFactory
应在为了得到一个实例实现工厂模式UserManager
每个请求的应用程序.否则您将获得以下异常:
在创建模型时不能使用上下文.如果在OnModelCreating方法中使用上下文,或者同时由多个线程访问相同的上下文实例,则可能抛出此异常.请注意,DbContext和相关类的实例成员不保证是线程安全的.
就这样.
归档时间: |
|
查看次数: |
18267 次 |
最近记录: |