0

How can i assign role to a user in asp.net mvc3 application ?

i tried doing following

   public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            if (model.user_id == "admin" && model.password == "admin")
            {
                 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                    1,
                                                    "admin",
                                                    DateTime.Now,
                                                    DateTime.Now.AddMinutes(30),
                                                    false,
                                                    "admin",
                                                    FormsAuthentication.FormsCookiePath);


                return JavaScript("window.location.replace('/Home/');");
            }

            else
            {
                return Content("Invalid User Id or Password.");
            }
        }
        else
        {
            return View(model);
        }
    }

Now when i try to get the user role in any views, it never gives me the role as admin. How do i assign role after login ?

4

1 回答 1

0

为什么要访问视图上的用户角色?您不应该这样做,如果有任何特定需求,从数据库中获取角色后,将角色存储在模型中,以便您可以通过模型属性读取视图中的角色。

如果您不想更改模型,那么您也可以将属性添加到 ViewBag。例如 ViewBag.UserRoles = "admin";

我注意到的另一件事是,您也没有创建主体对象并将其分配给 HttpContext.User 以便您可以基于此执行授权。

于 2013-02-02T07:26:17.823 回答