身份验证和登录页面 - 如何进行身份验证?

时间:2015-09-21 10:39:31

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

我正在阅读:FormsAuthentication with Razor not working但可能会从回复中得到一些错误。

using  System.Web.Security;

[HttpPost]
public ActionResult Index(LoginModel model, string name, string pw)
{
    if (ModelState.IsValid && Membership.ValidateUser(name, pw))
    {
        if (!String.IsNullOrEmpty(pw) && !String.IsNullOrEmpty(name))
        {
            try 
            {
                var db = new UsersDBContext();
                var Name = (from Users in db.Users
                            where Users.Name == name && Users.Password == pw
                            select Users.CustomerId).Single();

                if (Name != 0)
                {
                    string myIDString = Name.ToString();
                    Session["myID"] = myIDString;
                    return Redirect("/LogModels/Index");
                }
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
        }
        else
        {
            //Add alert -> password does not exist/is wrong etc.
        }
    }
    return Redirect("/");
}

问题在于我尝试添加

&& Membership.ValidateUser(model.UserName, model.Password)

我收到了以下错误。

  

当前上下文中不存在成员资格

我对此很新,所以请尽可能以非常简单的方式解释。

提前致谢。

修改

LoginModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace WebPortalMVC.Models
{
    [Table("Users")]
    public class UsersModel
    {
        [Key]
        public int Id { get; set; }

        [Display(Name = "Name")]
        public string Name { get; set; }

        //[DataType(DataType.Password)]
        [Display(Name = "Password")]
        [DataType(DataType.Password)]
        public string Password { get; set; }
        /*
        [Display(Name = "Remember me on this computer")]
        public bool RememberMe { get; set; }
        */
        public int CustomerId { get; set; }
    }  
    public class UsersDBContext : DbContext
    {
        public UsersDBContext() : base("MySqlConnection")
        {
        }

        public DbSet<UsersModel> Users { get; set; }
    }
}

查看(不是全部)

<div id="login">
                <h1>Web Portal</h1>

                @using (Html.BeginForm())
                {
                    <p>
                        @Html.TextBox("name", "", new { type = "email", placeholder = "example@email.com" })
                    </p>
                    <p>
                        @Html.Password("pw",  "", new { type = "password", placeholder = "Password" })
                    </p>
                        <input type="submit" id="loginsubmit" value="Log in" onclick="emptypasswordcheck()" />
                }
            </div>
        </div>

**编辑2:**根据@FreshBM答案添加了代码。

1 个答案:

答案 0 :(得分:2)

Membership.ValidateUser位于System.Web.Security命名空间中。因此,根据您的错误消息判断,我认为您没有引用System.Web.Security。

尝试添加它。

编辑:

此外,您需要更改对ValidateUser的调用,因为您在索引操作中没有模型作为参数。相反,你有两个参数,名称和密码:

Membership.ValidateUser(name, pwd)

或者如果你想使用LoginModel add using directive:

using WebPortalMVC.Models;

提示:可能最简单的方法是重新发现缺少使用指令的问题,右键单击类名并从上下文菜单中使用Resolve,或者您可以使用键盘快捷键:Ctrl + .

您可以参考本教程在MVC中配置成员资格提供程序:

http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF

http://www.codeguru.com/csharp/article.php/c18813/Using-Forms-Authentication-in-ASPNET-MVC-Applications.htm