使用MySQL库成员提供程序的类库

时间:2015-09-29 01:23:01

标签: mysql asp.net asp.net-membership membership-provider

我正在尝试将ASP.NET成员资格提供程序与MySQL数据库一起使用并取得了成功。我的解决方案目前包含一个ASP.NET MVC项目,该项目已配置为使用MySQL,另一个项目处理对数据库的所有调用,我还要在其中处理成员函数,如创建和验证用户。

这两个项目都安装了MS .NET EnityFramework v6.1.3,Microsoft.AspNet.Identity.EntityFramework v2.2.1和MySql.Data.Entity v6.9.7。

我按照http://k16c.eu/2014/10/12/asp-net-identity-2-0-mariadb/的说明配置了ASP.NET项目。我的“web.config”配置如下;

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <configSections> 
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 
    </configSections> 
    <connectionStrings> 
        <remove name="LocalMySqlServer" /> 
        <add name="LocalMySqlServer" 
            connectionString="Server=localhost; Database=rb-web; Uid=root; Pwd=password; Convert Zero Datetime=True; Allow User Variables=True;" 
            providerName="MySql.Data.MySqlClient" /> 
    </connectionStrings> 
    <system.web> 
        <compilation debug="true" targetFramework="4.5" /> 
        <httpRuntime targetFramework="4.5" /> 
    </system.web> 
    <entityFramework> 
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> 
        <parameters> 
            <parameter value="mssqllocaldb" /> 
        </parameters> 
        </defaultConnectionFactory> 
        <providers> 
            <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 
            <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> 
        </providers> 
    </entityFramework> 
    <system.data> 
        <DbProviderFactories> 
            <remove invariant="MySql.Data.MySqlClient" /> 
            <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.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> 
        </DbProviderFactories> 
    </system.data> 
</configuration> 

http://k16c.eu/2014/10/12/asp-net-identity-2-0-mariadb/处的指令需要创建两个新类ApplicationUser.cs和ApplicationContext.cs,但这些基本上复制了已包含在我的项目中的IdentityModels.cs中的代码。身份模型代码是;

using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using MySql.Data.Entity;

namespace RB.Client.Models
{
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }
    }

    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext() : base("LocalMySqlServer", throwIfV1Schema: false) { }
        public ApplicationDbContext(string connStringName) : base(connStringName, throwIfV1Schema: false) { }
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // Primary keys can easily get too long for MySQL's (InnoDB's) stupid 767 bytes limit.
            // The following lines rewrite the generation to keep those columns "short" enough.
            modelBuilder.Entity<IdentityRole>()
                .Property(c => c.Name)
                .HasMaxLength(128)
                .IsRequired();

            // Declare the table name here, otherwise IdentityUser will be created.
            modelBuilder.Entity<ApplicationUser>()
                .ToTable("AspNetUsers")
                .Property(c => c.UserName)
                .HasMaxLength(128)
                .IsRequired();
        }
    }
}

完成这些更改后,我从Package Manager控制台运行了Enable-Migrations并修改了Configuration.cs类,如下所示;

namespace RB.Client.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<RB.Client.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
        }

        protected override void Seed(RB.Client.Models.ApplicationDbContext context)
        {
        }
    }
}

然后我从包管理器控制台运行了Add-Migration“Initial”和Update-Database命令,该命令在MySQL中创建了aspnetroles,aspnetuserclaims,aspnetuiserlogins,aspnetuserroles和aspnetusers表。

然后我在持久性项目中使用以下代码;

public UserDto RegisterUser(UserDto user) 
{ 
    var appUser = Membership.CreateUser(user.Email, user.Password); 
} 

提出异常;

“无法初始化提供程序。缺少或不正确的架构。” “MySql.Web在MySql.Web.Common.SchemaManager.CheckSchema(String connectionString,NameValueCollection config) at MySql.Web.Security.MySQLMembershipProvider.Initialize(String name,NameValueCollection config) 在System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings,Type providerType)“

但是,如果我将以下条目添加到“web.config”;

<system.web>
    <roleManager defaultProvider="MySQLRoleProvider">
        <providers>
            <remove name="MySQLRoleProvider" />
            <add name="MySQLRoleProvider"
                 type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"
                 applicationName="/RBWeb"
                 description="RB Role Provider"
                 connectionStringName="LocalMySqlServer"
                 writeExceptionsToEventLog="True"
                 autogenerateschema="True"
                 enableExpireCallback="False" />
        </providers>
    </roleManager>

    <membership defaultProvider="MySQLMembershipProvider">
        <providers>
            <remove name="MySQLMembershipProvider" />
            <add name="MySQLMembershipProvider"
                 type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"
                 applicationName="/RbWeb"
                 description="RB Membership Provider"
                 connectionStringName="LocalMySqlServer"
                 writeExceptionsToEventLog="True"
                 autogenerateschema="True"
                 enableExpireCallback="False"
                 enablePasswordRetrieval="False"
                 enablePasswordReset="True"
                 requiresQuestionAndAnswer="False"
                 requiresUniqueEmail="True"
                 passwordFormat="Hashed"
                 maxInvalidPasswordAttempts="5"
                 minRequiredPasswordLength="6"
                 minRequiredNonalphanumericCharacters="1"
                 passwordAttemptWindow="10"
                 passwordStrengthRegularExpression="" />
        </providers>
    </membership>

    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
</system.web>

成功创建用户并返回System.Web.Security.MembershipUser对象。但是,调用现在在数据库中生成了许多新表,my_aspnet_users,my_aspnet_roles等,以及所有用于配置文件,个性化和会话管理的表,即使这些选项未包含在web.config设置中,用户记录是在这些表中创建的。我的网站和持久性项目之间似乎存在脱节。

我已经回顾了我在MySQL中可以找到的所有文章,但是这些文章似乎都已过时且没有任何帮助。在这一点上,我现在正在编写一个自定义成员资格提供程序来试图解决这些问题,但说实话,我也在考虑放弃MySQL,因为我遇到了试图使其工作的问题。

0 个答案:

没有答案