如何在 ASP.NET MVC4 中初始化简单的成员资格
嗨,我正在研究 ASP.NET MVC4。如您所知,ASP.NET MVC4 中禁用了成员资格/身份验证机制;如果我们想启用它,我们需要:
1)编辑后续行(在类SimpleMembershipInitializer的构造函数中,文件InitializeSimpleMembershipAttribute.cs)
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "users", "id", "username", autoCreateTables: true);
2) 在您的 Web.Config 部分中添加一个新密钥。
<appSettings>
<add key="enableSimpleMembership" value="true" />
...
</appSettings>
注意:我已经在我的数据库中创建了表“用户”,DefaultConnection 设置正确。
编辑:让“DefaultConnectionString”成为
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-SimpleAuthenticationMvc4-20140209174604;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
当我尝试在我的 Web 应用程序中“登录”时,我在调用 EnsureInitialized() 时收到 TargetInvocationException:这里是我的 InitializeSimpleMembershipAttribute 类的完整源代码:
/* class MyApp.Filters.InitializeSimpleMembershipAttribute */
namespace MyApp.Filters
{
[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
// HERE i _always_ get TargetInvocationException
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
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();
}
}
/* DefaultConnection and table 'users' should/seems to be OK */
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "users", "id", "username", autoCreateTables: true);
}
catch (Exception ex)
{
...
}
}
}
}
}
有人建议我这个错误可能意味着简单的成员资格在应用程序的另一部分被初始化,但我不明白这可能发生在哪里:这是我的 global.asax.cs 的文本:
/* file global.asax.cs */
namespace MyApp
{
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();
}
}
}
如您所见,没有什么奇怪的。我也尝试在文件 global.asax.cs 中移动,正如这里所建议的那样,但即便如此我也得到了同样的例外。
我没有特殊要求:我只想登录我的 MVC 4 应用程序,就像我之前编写的 MVC3 应用程序一样。
谁能建议我错误在哪里?
谢谢!
它