我正在阅读: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 = "[email protected]" })
                    </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答案添加了代码。

最佳答案

Membership.ValidateUser位于System.Web.Security命名空间中。因此,从您收到的错误消息来看,我认为您没有引用System.Web.Security。

尝试添加它。

编辑:

另外,您还需要更改对ValidateUser的调用,因为在Index操作中没有将模型作为参数。相反,您有两个参数,即name和pwd:

Membership.ValidateUser(name, pwd)


或者,如果您要使用LoginModel,请使用指令添加:

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

07-28 11:11