我正在尝试编写一个控制台应用程序来创建和填充 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/