使用实体框架在MVC4中进行用户验证

时间:2013-12-27 06:32:33

标签: entity-framework asp.net-mvc-4

我正在尝试验证用户,而Http Post代码位于下方。我研究了一些网站,得到了this。所以我提到了它。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Admin admin)
{                                         //admin is the model
    if(ModelState.IsValid && IsValidAdmin(admin.Username, admin.Password))
    {
        return Redirect("http://www.google.com");
    }
    return View();
}

和IsValidAdmin是一种方法如下:

public bool IsValidAdmin(Admin admin)
{
    bool isValidAdmin = false;
    //here i want to check the username and password if exists in the database;
    //using (var db = new DbContext(AdminContext) )
    {
        var myUser = db.admin.FirstOrDefault(u => u.Username == admin.Username
    }
    return isValidAdmin;
}

但我不确定如何初始化db。我的模型是Admin,Context是AdminContext

我正在使用Entity框架和全新到VS .net和实体框架,但熟悉MVC。

请帮忙

3 个答案:

答案 0 :(得分:1)

您的AdminContext类继承自DBContext。

public bool IsValidAdmin(Admin admin)
{
    bool isValidAdmin = false;
    //here i want to check the username and password if exists in the database;
    using (var db = new AdminContext() )
    {
        var myUser = db.admin.FirstOrDefault(u => u.Username == admin.Username)
        if(myUser != null)
        {
            // do your check here.
        }
    }
    return isValidAdmin;
}

答案 1 :(得分:0)

public bool IsValidAdmin(Admin admin)
{
    bool isValidAdmin = false;
    //here i want to check the username and password if exists in the database;
    using (var db = new AdminContext() )
    {
        return db.admin.Where(u => u.Username == admin.Username).Count() == 0;

    }

}

答案 2 :(得分:0)

您需要检查组合登录&&密码。如果存在,请允许登录。

logins lg = null;
using (AdminContext db = new AdminContext())
{
    lg = db.logins.FirstOrDefault(x =>
         x.Username == Username.Trim()
         && x.login_pass == md5.Trim()
    );
}
return lg == null;