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

时间:2015-09-24 11:30:35

标签: asp.net initialization aspnetdb

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

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数据库?目标是设置从其他数据库中提取的名称,其他属性等

1 个答案:

答案 0 :(得分:2)

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

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

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

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

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