我正在尝试编写一个控制台应用程序,该应用程序将为web应用程序创建和填充身份验证数据库。它应该是部署例程的一部分。下面的代码可以部分工作:
using System.Web.Management;
using System.Web.Security;
namespace InitAspnetdbAppRolesAndUsers
{
class Program
{
static string SQLServerName = @"COMPUTERSQLINSTANCE";
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_snippetsInitAspnetdbAppRolesAndUsersProgram.cs:line 23
控制台应用程序也可以添加PreApplicationStartMethodAttribute
吗?如果是,如何做到这一点?是否有其他方法来填充asbnetdb
数据库?目标是设置从其他数据库
PreApplicationStartMethodAttribute
是ASP的一部分。并且只会被ASP.NET调用。它不会在控制台应用程序中做任何事情。
还有另一种启用角色的方法,请参阅本教程。基本上,你需要添加到App.config中的配置是这样的:
<configuration>
<system.web>
<roleManager enabled="true" />
</system.web>
</configuration>
当然,您还需要正确配置角色管理器,使其指向正确的数据库。