你需要WebSecurity.InitializeDatabaseFile
告诉 MVC.NET 你已经有一个数据库和一个用户表。然后,确保提供程序在初始化时使用它。因此,创建一个ActionFilterAttribute
可确保初始化 Simple Membership 提供程序的方法,例如:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
try
{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "UserId", "UserName", autoCreateTables: true);
}
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
然后你需要注册过滤器:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new InitializeSimpleMembershipAttribute());
}
}
编辑:感谢建设性的批评,我已经删除了用属性装饰控制器的代码,因为在全局范围内添加它已经解决了这个问题。如果您决定不全局使用它,您将需要用它来装饰其他控制器,因为正如在这个问题中所解释的那样,您会注意到用户可能会使用 cookie 进行身份验证并重定向到其他控制器,而无需先通过您的 AccountController。
此外,Jon Galloway在这篇文章中展示了如何使用以下方法指向现有数据库:
WebSecurity.InitializeDatabaseFile("SecurityDemo.sdf", "Users", "UserID", "Username", true);