Databasefirst ASP.NET MVC4登录

时间:2014-04-29 11:22:02

标签: c# asp.net asp.net-mvc-4 login simplemembership

我正在开发一个包含现有数据库的项目(不是codefirst)。我正在尝试实施登录/注册/注销,并在此网站中集成社交媒体。

然而,我认为我做错了。我总是得到“无法初始化ASP.NET简单成员资格数据库” - 错误。

所以对于记录,如果用户在数据库中,我想检查给定的emailadress和paswoord

这是我输入e-mailaddress和pasword登录的视图。

 @model DAL_EF.Account

@{
    ViewBag.Title = "Politici Online | Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Login</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.Js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{ 
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Enter username and password</legend>

        <div class="editor-label">
            Emailadres
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.emailadres)
            @Html.ValidationMessageFor(model => model.emailadres)
        </div>

        <div class="editor-label">
            Wachtwoord
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.wachtwoord)
            @Html.ValidationMessageFor(model => model.wachtwoord)
        </div>

        <p>
            <input type="submit" value="Login" />
        </p>
    </fieldset>
}

<section class="social" id="socialLoginForm">
    <h2>Use another service to log in.</h2>
    @Html.Action("ExternalLoginsList", new { ReturnUrl = ViewBag.ReturnUrl })
</section>

这是控制器:

 //
    // POST: /Account/Login/
    [HttpPost]
    public ActionResult Login(DAL_EF.Account model, string returnUrl)
    {
        // Lets first check if the Model is valid or not
        if (ModelState.IsValid)
        {
            using (PoliticiOnlineEntities entities = new PoliticiOnlineEntities())
            {
                string username = model.emailadres;
                string password = model.wachtwoord;

                bool userValid = entities.Account.Any(user => user.emailadres == username && user.wachtwoord == password);

                // gebruiker gevonden in de database!
                if (userValid)
                {

                    //FormsAuthentication.SetAuthCookie(username, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
        }

        //als we zover zijn geraakt, dan is er iets gefaald ... We laten het form terug zien
        return View(model);
    }

这是InitializeSimpleMembershipAttribute:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public 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();
                    }
                }

                if (!WebSecurity.Initialized)
                {
                    WebSecurity.InitializeDatabaseConnection("PoliticiOnlineEntities", "Account", "accountID", "emailadres", 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);
            }
        }
    }
}

这是连接字符串(我删除了敏感信息):

<add name="PoliticiOnlineEntities" connectionString="metadata=res://*/PoliticiOnline.csdl|res://*/PoliticiOnline.ssdl|res://*/PoliticiOnline.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=*****;initial catalog=****;persist security info=True;user id=********;password=*****;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

0 个答案:

没有答案