在调用“WebSecurity”类的任何其他方法之前,必须调用“WebSecurity.InitializeDatabaseConnection”方法

时间:2013-07-24 15:52:48

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-membership

每次我使用Visual Studio重新启动调试时,我都会遇到这个错误的错误:

  

您必须调用“WebSecurity.InitializeDatabaseConnection”方法   在调用“WebSecurity”类的任何其他方法之前。这个   call应该放在你的root的_AppStart.cshtml文件中   站点。

但这是每次,当我将应用程序部署到prod时。我在这里随机地得到了这个错误。

我确实放了正确的标签:

[Authorize(Roles = "admin")]
[InitializeSimpleMembership]
public class IndexController : Controller

到控制器,这是过滤器的方式。它只是不想工作。

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using MeetingTaskManagement.Models;
using WebMatrix.WebData;

namespace MeetingTaskManagement.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
            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();
                        }
                    }

                    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);
                }
            }
        }
    }
}

有人可以帮我解决这个问题吗?

6 个答案:

答案 0 :(得分:65)

从控制器中删除SimpleMemberShip属性并将其删除。将以下内容添加到global.asax。

    private static SimpleMembershipInitializer _initializer;
    private static object _initializerLock = new object();
    private static bool _isInitialized;

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
    }

    public class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            using (var context = new UsersContext())
                context.UserProfiles.Find(1);

            if (!WebSecurity.Initialized)
                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
        }
    }

答案 1 :(得分:9)

为简化Global.asax,您可以将初始化代码放入class AuthConfig,如下所示:

public static class AuthConfig
{
    private static SimpleMembershipInitializer _initializer;
    private static object _initializerLock = new object();
    private static bool _isInitialized;

    public static void RegisterAuth()
    {
        // Ensure ASP.NET Simple Membership is initialized only once per app start
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);

        // To let users of this site log in using their accounts from other sites such as Microsoft, Facebook, and Twitter,
        // you must update this site. For more information visit http://go.microsoft.com/fwlink/?LinkID=252166

        //OAuthWebSecurity.RegisterMicrosoftClient(
        //    clientId: "",
        //    clientSecret: "");

        //OAuthWebSecurity.RegisterTwitterClient(
        //    consumerKey: "",
        //    consumerSecret: "");

        //OAuthWebSecurity.RegisterFacebookClient(
        //    appId: "",
        //    appSecret: "");

        //OAuthWebSecurity.RegisterGoogleClient();
    }

    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);
            }
        }
    }
}

答案 2 :(得分:4)

我只是将[InitializeSimpleMembership]切换到HomeController,并从AccountController中删除它。因为初始化是以懒惰的方式进行的..我只是想赶紧...它有效!

答案 3 :(得分:1)

通过为成员资格提供程序和我的域模型使用单个上下文,我是一个聪明人。原来那是问题所在;您不能在单个上下文中使用成员资格提供程序和域类。

你需要有两个背景。

答案 4 :(得分:0)

要求只是调用WebSecurity Database Connection,您可以执行以下工作:

var WebSecDBContx = new UsersContext();
var CreatedByUser = WebSecDBContx.UserProfiles.Find(UserID);
string CreatedByUserName = CreatedByUser.UserName;

答案 5 :(得分:0)

为什么不在项目根目录中创建_AppStart.cshtml,并将初始化代码放在那里,如错误消息所示。

@{WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("DefaultConnection", "TableName", "ColumnId", "ColumnName", autoCreateTables: false);}