如何使用 ASP.NET Identity 和 MySQL Provider 设置应用程序






4.97/5 (23投票s)
设置一个实现 ASP Identity 并使用 Entity Framework 将 MySQL 作为数据库的 ASP.NET 应用程序。
引言
我使用 Visual Studio 2013 开发了示例代码。使用的应用程序框架是 .NET 4.5。
使用的数据库是 MySQL。我下载并安装了 MySQL Installer 5.6.19,可以在此处找到。
这会安装所有必需的文件,包括 MySQL 版本 1.1.4 连接器。您甚至可以从 Server Explorer -> Data Connections -> Right click on Add Connection 中选择 MySql。
下载示例项目 (VS2013MySql
) 后,解压缩,打开文件夹,然后单击 VS2013MySql.sln 在 Visual Studio 2013 中打开它。您需要更改 Web.config 中的连接字符串才能在您自己的 MySql 环境中运行它。
对于熟悉 Visual Studio(2012 和 2013)的开发人员来说,使用已设置的 LocalDB 进行开发相当容易。然后,开发人员可以轻松地迁移到 MS SQL Server 进行生产。
本文档适用于希望使用 MySQL 开发其 ASP.NET Web 应用程序的用户。
背景
有时,开发人员可能希望使用免费的开源数据库来降低使用其他数据库(例如 MS SQL Server、Oracle DB 等)的成本。或者,开发人员可能有需要使用 mySql 进行工作的客户。无论原因如何,以下内容将帮助您进行设置。
使用代码
在 VS 2013 中创建一个新项目。选择 ASP.NET Web Application。在顶部,选择 .NET framework 4.5.1,为您的应用程序命名,然后单击 Next。
在下一个屏幕上,选择 Web Forms 模板(本文档基于 WebForms 应用程序。但是,为 MVC 应用程序设置 MySQL 的步骤是相似的),并将身份验证保留为 Individual User Accounts。单击“OK”以初始化应用程序进行开发。
在 Solution Explorer 中,右键单击“References”,然后单击“Add Reference”。我上面提到的 MySql 安装程序应该已在您的计算机上安装了一些重要的 .MySql 文件。我们将选择其中 3 个添加到我们的引用中。
在 Reference Manager 中,转到 Assemblies -> Extensions 并单击:MySql.Data, MySql.Data.Entity.EF6 and MySql.Web。(MySql.Data 和 MySql.Web 的版本是 6.8.3.0)
您的引用现在应该如下所示:
下一步是打开 **Web.config** 文件并进行以下更改。(可下载的解决方案应该能为您提供指导)
1. 更改连接字符串
<connectionStrings>
<add name="DefaultConnection" connectionString="server=localhost;User Id=root;password=password;Persist Security Info=True;database=aspmysql"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
相应地更改服务器名称、Id、密码和数据库。要轻松获取所需的连接字符串,请从 Server Explorer -> Data Connections -> Right click on Add Connection 中选择 MySql。
根据需要输入详细信息,选择数据库并测试连接。然后单击“OK”。在 Server Explorer 中,当您单击已添加的数据库时,您应该会在 Visual Studio 屏幕右下角的 Properties 窗口中看到连接字符串。
2. 更改 membership
<membership defaultProvider="MySqlMembershipProvider">
<providers>
<clear />
<add name="MySqlMembershipProvider"
type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web"
connectionStringName="DefaultConnection"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/"
autogenerateschema="true" />
</providers>
</membership>
3. 更改 profile
<profile> <providers> <clear /> <add type="MySql.Web.Security.MySqlProfileProvider, MySql.Web" name="MySqlProfileProvider" applicationName="/" connectionStringName="DefaultConnection" autogenerateschema="true" /> </providers> </profile>
4. 更改 role manager
<roleManager enabled="true" defaultProvider="MySqlRoleProvider"> <providers> <clear /> <add connectionStringName="DefaultConnection" applicationName="/" name="MySqlRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" autogenerateschema="true" /> </providers> </roleManager>
5. 将旧的 Entity Framework 更改为
<entityFramework>
<providers>
<provider invariantName="MySql.Data.MySqlClient"
type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient"></remove>
<add name="MySQL Data Provider"
invariant="MySql.Data.MySqlClient"
description=".Net Framework Data Provider for MySQL"
type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
我们现在将启用 migrations。
转到菜单项 View -> Other Windows -> 单击“Package Manager Console”。在控制台提示符下输入“enable-migrations”并按 Enter。
一个新文件夹 Migrations 将被放在您的解决方案中(请检查 Solution Explorer),以及一个名为“Configuration.cs”的新文件。
Entity Framework Code First 使用 Migration History 来跟踪模型更改并确保数据库与概念模式之间的一致性。Migration History 表 **__migrationhistory** 的主键对于 MySql 来说太大了。
修复方法
在 migration 文件夹下,添加一个名为 MySqlHistoryContext.cs 的新类,并添加以下代码:
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Migrations.History;
namespace VS2013MySql.Migrations
{
public class MySqlHistoryContext : HistoryContext
{
public MySqlHistoryContext(DbConnection connection, string defaultSchema)
: base(connection, defaultSchema)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
}
}
}
在同一个 migration 文件夹下,对 Configuration.cs 文件进行更改,使其如下所示:
namespace VS2013MySql.Migrations
{
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<VS2013MySql.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
// register mysql code generator
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
SetHistoryContextFactory("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
}
protected override void Seed(VS2013MySql.Models.ApplicationDbContext context)
{
}
}
}
我们现在需要创建一个自定义数据库初始化程序,因为 MySQL provider 不支持 Entity Framework migrations。
向项目中添加一个名为 MySqlInitializer.cs 的新类文件,并将其代码更改为:
using VS2013MySql.Models;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
namespace VS2013MySql
{
public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{
public void InitializeDatabase(ApplicationDbContext context)
{
if (!context.Database.Exists())
{
// if database did not exist before - create it
context.Database.Create();
}
else
{
// query to check if MigrationHistory table is present in the database
var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
string.Format(
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'",
"aspmysql"));
// if MigrationHistory table is not there (which is the case first time we run) - create it
if (migrationHistoryTableExists.FirstOrDefault() == 0)
{
context.Database.Delete();
context.Database.Create();
}
}
}
}
}
上面的文件在第 24 行(对于我的项目):将“aspmysql”更改为您正在使用的 MySql 数据库的名称。
在我的 Solution Explorer 中,这 3 个文件看起来像这样:
在 Solution Explorer 的 Models 文件夹下,将 IdentityModel.cs 文件代码更改为:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System.Web;
using System;
using VS2013MySql.Models;
using System.Data.Entity;
namespace VS2013MySql.Models
{
// You can add User data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.SetInitializer(new MySqlInitializer());
}
}
将 Helpers 部分保持原样。
您猜怎么着?我们完成了!
要测试您的应用程序,请按 Ctrl + F5 进行构建和运行。
然后单击页面右上角的 **Register** 选项卡并注册一个新用户。您应该会在导航菜单上看到“Welcome @user!”。
现在,如果您转到 MySql workbench(我使用 SQLyog),您应该会看到新创建的表。
如果查看“**aspnetusers**”表中的数据,您将看到新创建的用户的信息。
我从开发者论坛上零散的代码片段中整理了这些。这个教程帮助很大,即使他们展示了到 Azure 的 MySql 连接。我希望它能对某些人有所帮助。