MVC自定义登录身份验证

时间:2018-05-20 04:36:11

标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-3 model-view-controller

您好我正在使用MVC开发应用程序,我遇到登录问题,我想知道如何根据用户角色管理登录。

虽然登录工作正常,但我需要确定用户发送到不同页面的角色

我的数据库中有一个表调用Employee,一列是调用IdPosition,它被称为另一个表调用Position。

这是我的代码

[HttpPost]
    public ActionResult Autorizacion(Pepitos.Models.Employee employee)
    {
        using (pepitosEntities db = new pepitosEntities())
        {
            var userDetails = db.Employees.Where(x => x.Username == employee.Username && x.Password == employee.Password).FirstOrDefault();

            if (userDetails == null)
            {
                employee.ErrorLoginMensaje = "Username or Password incorrect";
                return View("Login",employee);
            }
            else
            {
                Session["IdEmployee"] = userDetails .IdEmployee;
                Session["name"] = userDetails.Name;
                return RedirectToAction("EmployeesIndex", "EmployeesHome");
            }
        }

    }

1 个答案:

答案 0 :(得分:1)

现在您需要做的是在用户名和密码匹配后检查角色,然后相应地重定向。因为我假设您在数据库表中有角色列以及用户名和密码。

 using (pepitosEntities db = new pepitosEntities())
    {
        var userDetails = db.Employees.Where(x => x.Username == employee.Username && x.Password == employee.Password).FirstOrDefault();

        if (userDetails == null)
        {
            employee.ErrorLoginMensaje = "Username or Password incorrect";
            return View("Login",employee);
        }
        else
        {

            var userRole=userDetails.role; //get the role of the user i.e whether user is admin or any other role

            if(userRole=="Admin")
            {
               Session["IdEmployee"] = userDetails .IdEmployee;
               Session["name"] = userDetails.Name;
               return RedirectToAction("EmployeesIndex","EmployeesHome");
            }
            else if(userRole=="User")
            {
                Session["IdUser"] = userDetails .IdUser;
                Session["name"] = userDetails.Name;
                return RedirectToAction("UserIndex","UserHome");
            }
            //and so on
        }
    }
希望它有所帮助!