23

Everytime I restart Debugging with Visual Studio I get this freaking error:

You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.

But that is everytime, and when i deploy the app to prod. I get this error here and then, randomly.

I do put the proper tag :

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

to controller and here is the filter the way it is. It just doesnt wanna work.

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

can someone help me sort this out?

4

6 回答 6

66

从控制器中删除 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);
        }
    }
于 2013-07-25T09:30:57.427 回答
10

为了简化您的 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);
            }
        }
    }
}
于 2013-09-16T11:26:08.520 回答
4

我只是将 [InitializeSimpleMembership] 切换到 HomeController,然后从 AccountController 中删除它。因为初始化是以一种懒惰的方式进行的..我只是想匆匆忙忙..它奏效了!!!

于 2013-11-23T21:37:10.170 回答
1

通过为会员提供者和我的域模型使用单一上下文,我成为了一个聪明人。事实证明这是问题所在。您不能在单个上下文中使用成员资格提供程序和域类。

你需要有两个上下文。

于 2013-07-24T19:31:10.210 回答
0

要求仅调用 WebSecurity 数据库连接,您可以执行以下操作:

var WebSecDBContx = new UsersContext();
var CreatedByUser = WebSecDBContx.UserProfiles.Find(UserID);
string CreatedByUserName = CreatedByUser.UserName;
于 2014-09-27T09:35:36.823 回答
0

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

@{WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("DefaultConnection", "TableName", "ColumnId", "ColumnName", autoCreateTables: false);}
于 2017-02-15T18:11:42.837 回答