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

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

最佳答案

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

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

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

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

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

关于asp.net - 为 Web 应用程序(角色、用户)初始化 `aspnetdb` 数据库的推荐方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32760227/

相关文章:

asp.net - 建立与 SQL Server 的连接时出现与网络相关或特定于实例的错误

sql - 将 ASPNETDB.mdf 上传到共享主机?

c# - Gridview Format Field as Phone Number 但有些结果是 4 digit extension,如何处理?

asp.net - 向 asp.NET RadioButton 控件添加自定义属性

c++ - 了解 C++ 中的 vector 初始化

c++ - 这种初始化语法在即将到来的 c++0x 标准中有效吗?

asp.net - 如何在 ASP.NET 上上传 10gb 文件

asp.net - 需要购物车建议

C++ 初始化静态堆栈

asp.net - ASPNETDB管理工具