我正在尝试根据用户的角色将用户重定向到页面。以下是控制器中的登录代码:
[HttpPost]
public ActionResult Login(User model)
{
// Lets first check if the Model is valid or not
if (ModelState.IsValid)
{
using (AuthenticationAppEntities1 entities = new AuthenticationAppEntities1())
{
string username = model.Username;
string password = model.Password;
// Now if our password was enctypted or hashed we would have done the
// same operation on the user entered password here, But for now
// since the password is in plain text lets just authenticate directly
bool userValid = entities.Users.Any(user => user.Username == username && user.Password == password);
// User found in the databases
if (userValid)
{
FormsAuthentication.SetAuthCookie(username, false);
if (Roles.IsUserInRole(model.Roles, "admin"))
{
return RedirectToAction("Home", "Authentication");
}
else
{
return RedirectToAction("HomeAdmin", "Authentication");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
正如您在代码中看到的,我使用if来根据用户的角色重定向用户。但是,model.Roles包含一个空值,因为控制器只从登录页面获取用户名和密码。我是如何获得经过身份验证的用户角色的简单想法?我想通过用户名搜索它,但不确定这是否是最好的解决方案。
答案 0 :(得分:1)
您可以获取用户的角色,然后将其与“' admin'进行比较。然后相应地重定向。
答案 1 :(得分:0)
老实说,我甚至不确定你是如何在第一时间运行的。 Roles.IsUserInRole
的方法签名是:
Roles.IsUserInRole(string username, string role);
传递model.Roles
既不是字符串,也不是用户名,如果它是字符串。