从MVC4迁移到MVC5并且也想使用ASP.NET Identity但是我很难找到任何涵盖我认为我需要迁移Identity的所有内容的东西。 Migrating an Existing Website from SimpleMembership to ASP.NET Identity建议我需要做的就是创建一个ApplicationUser
并迁移数据,其他网络搜索会给我提供sql脚本和passowrd哈希建议。但在我跳入之前,我还有其他松散的目标需要清理。
首先 - 我有代码在我的Seed方法中初始化会员系统:
if (!WebSecurity.Initialized)
WebSecurity.InitializeDatabaseConnection(Config.ConnectionStringName,
Config.UsersTableName,
Config.UsersIDColumn,
Config.UserNameColumn,
autoCreateTables: true);
那么需要走对吗?
第二 - 看起来我需要一个IdentityDbContext
。那么我应该改变现有的上下文来继承它吗?
即。而不是我当前的代码public class SID2013Context : DbContext
执行此操作:public class SID2013Context : IdentityDbContext<ApplicationUser>
是否会生成一个迁移,用于创建支持ASP.NET Identity所需的新表?
一旦我完成了,我应该能够提取AccountController
,视图,ViewModel并启动为MVC5项目生成的代码。
有人可以在这里回答具体问题和/或指向更好的资源吗?
答案 0 :(得分:10)
我意识到我在我的问题中链接到的网站告诉您如何迁移到Identity
表,但仍然使用SimpleMembership
。我想在整个过程中使用Identity,所以我使用Visual Studio创建了一个空的MVC应用程序,这样我就可以复制我想要的代码并修复它。以下是我使登录和注销工作的步骤:
ApplicationUser.cs
添加到我的模型项目IdentityConfig.cs
添加到我的App_Start文件夹Startup.Auth.cs
添加到我的App_Start文件夹AccountController.cs
添加到我的Controllers文件夹(重命名为现有控制器)Startup.cs
添加到根文件夹AccountViewModels.cs
添加到ViewModels文件夹IdentityDbContext
(确实意味着在迁移中创建了新表)Add-Migration
给出了错误...&#34; EntityType IdentityUserRole没有定义键&#34; base.OnModelCreating
的调用解决了这个问题
Add-Migration
&amp; Update-Database
- 添加所需的表格UserProfile
中的自定义字段添加到ApplicationUser
并更新了数据库SecurityStamp
以防止在登录期间出现错误UserProfile
,SimpleRoleProvider
和RoleManager
类 - 在必要时替换代码。WebMatrix.Data
和WebMatrix.WebData
dll <roleManager enabled="true" defaultProvider="simple">
和<membership defaultProvider="simple">
醇>
步骤14中使用的Sql:
INSERT INTO dbo.aspnetusers (id
, email
, emailconfirmed
, passwordhash
, securitystamp
, phonenumber
, phonenumberconfirmed
, twofactorenabled
, lockoutenddateutc
, lockoutenabled
, accessfailedcount
, username
, organisationid
, firstname
, lastname
, inactive)
SELECT
u.id,
u.username Email,
m.isconfirmed EmailConfirmed,
m.password PasswordHash,
--SignInManager.PasswordSignInAsync (used in Login method)
--throws an exception http://stackoverflow.com/a/23354148/150342
NEWID() SecurityStamp,
u.telephone PhoneNumber,
CASE
WHEN u.telephone IS NULL THEN 0
ELSE 1
END PhoneNumberConfirmed,
0 TwoFactorEnabled,
NULL LockoutEndDateUtc,
0 LockoutEnabled,
m.passwordfailuressincelastsuccess AccessFailedCount,
u.username,
u.organisationid,
u.firstname,
u.lastname,
u.inactive
FROM dbo.userprofiles u
INNER JOIN dbo.webpages_membership m
ON m.userid = u.id
WHERE NOT EXISTS (SELECT
1
FROM dbo.aspnetusers
WHERE id = u.id)
INSERT INTO dbo.aspnetroles (id
, name)
SELECT
roleid,
rolename
FROM dbo.webpages_roles r
WHERE NOT EXISTS (SELECT
1
FROM dbo.aspnetroles
WHERE roleid = r.roleid)
INSERT INTO dbo.aspnetuserroles (userid
, roleid)
SELECT
userid,
roleid
FROM dbo.webpages_usersinroles ur
WHERE NOT EXISTS (SELECT
1
FROM dbo.aspnetuserroles
WHERE userid = ur.userid
AND roleid = ur.roleid)