我想访问SimpleMembershipProvider
的全部功能,例如ValidateUser
方法。
因此根据其documentation我不应该调用WebSecurity.InitializeDatabaseConnection()
进行初始化,而是启用标准成员资格和角色提供程序。
我的问题是:如何初始化SimpleMembershipProvider类
最后:可以访问SimpleMembershipProvider
或者如果有更好的解决方案,谢谢
答案 0 :(得分:3)
如何初始化SimpleMembershipProvider类
如果查看默认的ASP.NET MVC 4 Internet应用程序模板,AccountController将使用[InitializeSimpleMembership]
属性进行修饰。这是在这个样本中初始化的方式。这意味着您可以在通过帐户控制器之后使用它,而不是之前。如果您想在进行身份验证之前使用您的会员资格提供商,则可以使用Application_Start
方法执行相同操作。
答案 1 :(得分:2)
如果您要将InitializeSimpleMembershipAttribute
合并到Global.asax.cs
Application_Start
中,以便初始化SimpleMembershipProvider
而不会调用任何AccountController
路由...
......它看起来像这样:http://aaron-hoffman.blogspot.com/2013/02/aspnet-mvc-4-membership-users-passwords.html
// The using below is needed for "UsersContext" - it will be relative to your project namespace
using MvcApplication1.Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebMatrix.WebData;
namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "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);
}
}
}
}
}