为 Web 应用程序(角色、用户)初始化“aspnetdb”数据库的推荐方法?

The recommended way for initializing the `aspnetdb` database for the web app (roles, users)?

我正在尝试编写一个控制台应用程序来为 W​​eb 应用程序创建和填充身份验证数据库。它应该是部署例程的一部分。以下代码部分有效:

using System.Web.Management;
using System.Web.Security;

namespace InitAspnetdbAppRolesAndUsers
{
    class Program
    {
        static string SQLServerName = @"COMPUTER\SQLINSTANCE";
        static string ASPNETdbName = "aspnetdb";

        static void Main(string[] args)
        {
            // Create the aspnetdb database.
            SqlServices.Install(SQLServerName, ASPNETdbName, SqlFeatures.All);

            // Set the application.
            Membership.ApplicationName = "my_app";

            const string adminRoleName = "Administrator";
            const string adminUserName = "admin";
            const string adminPassword = "adminPa$$word1234";

            Roles.Enabled = true;

            if (!Roles.RoleExists(adminRoleName))
                Roles.CreateRole(adminRoleName);

            if (Membership.GetUser(adminUserName) == null)
                Membership.CreateUser(adminUserName, adminPassword);

            if (!Roles.IsUserInRole(adminUserName, adminRoleName))
                Roles.AddUserToRole(adminUserName, adminRoleName);
        }
    }
}

SqlServices.Install(SQLServerName, ASPNETdbName, SqlFeatures.All); 被执行,aspnetdb 空数据库创建没有问题。但是,Roles.Enabled = true; 崩溃(不是准确的英文措辞,已翻译)...

Unhandled exception: System.InvalidOperationException: The method can be called
only during initialization phase of the application, before it is launched.
Declare the method that will be called in the phase using the attribute
PreApplicationStartMethodAttribute.
   in System.Web.Compilation.BuildManager.ThrowIfPreAppStartNotRunning()
   in System.Web.Security.Roles.set_Enabled(Boolean value)
   in InitAspnetdbAppRolesAndUsers.Program.Main(String[] args) 
in D:\ASP_NET_snippets\InitAspnetdbAppRolesAndUsers\Program.cs:line 23

是否也可以为 控制台应用程序 添加 PreApplicationStartMethodAttribute?如果是,如何做到这一点?还有其他方法可以填充 asbnetdb 数据库吗?目标是设置从其他数据库中提取的名称、其他属性等

PreApplicationStartMethodAttribute 是 ASP.NET 的一部分,只会被 ASP.NET 调用。它不会在控制台应用程序中执行任何操作。

还有另一种启用角色的方法,请参阅 this tutorial

基本上,您需要添加到 App.config 的配置是这样的:

<configuration>
    <system.web>
        <roleManager enabled="true" />
    </system.web>
</configuration>

当然,您还需要正确配置您的角色管理器,使其指向正确的数据库。