InitializeSimpleMembership Attribute and SimpleMembership Exceptions

原文:https://blogs.msdn.microsoft.com/rickandy/2012/08/15/initializesimplemembership-attribute-and-simplemembership-exceptions/

The InitializeSimpleMembership Attribute ensures that before any membership (login/register) related functionality is run, that the membership database has been created. If the database is not yet created, the code will automatically create one. If the simple membership initialization fails, the Web Application can continue to run requests that don’t require membership.

Simple membership initialization failure can occur for the following reasons.

  1. The most common reason is the connection string to SQL Server is not valid. For example, you might not have SQL Server available. This is a frequent cause of failure in Azure. The ASP.NET MVC 4 templates by default use SqlExpress when created with Visual Studio 2010 and LocalDB when using Visual Studio 2012. SqlExpress is not installed on Azure and LocalDB does not run on Azure.
  2. Multiple DBContext objects on the same database.

The following code shows the InitializeSimpleMembership Attribute code that is added to a new ASP.NET MVC application. The code is found in the Filters folder:

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

namespace MvcV4.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);
                }
            }
        }
    }
}
 #region //
 策略一:数据库不存在时重新创建数据库
 //Database.SetInitializer<UsersContext>(new CreateDatabaseIfNotExists<UsersContext>());
 策略二:每次启动应用程序时创建数据库
 //Database.SetInitializer<UsersContext>(new DropCreateDatabaseAlways<UsersContext>());
 策略三:模型更改时重新创建数据库
 //Database.SetInitializer<UsersContext>(new DropCreateDatabaseIfModelChanges<UsersContext>());
 策略四:从不创建数据库
 //Database.SetInitializer<UsersContext>(null);
 #endregion




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值