2015-09-01 171 views
-1

這是我的新會員註冊,並在控制器登錄操作方法:授權角色不工作

public ActionResult SignUp() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult SignUp(User _user) 
    { 
     _user.Authorize = CustomRoles.RegisteredUser; 
     int lastuserid = entities.Users.Last().UserID; 
     _user.UserID = lastuserid + 1; 
     if (ModelState.IsValid) 
     { 
      Roles.AddUserToRole(_user.UserName, CustomRoles.RegisteredUser); 
      entities.Users.Add(_user); 
      entities.SaveChanges(); 
      RedirectToAction("Index"); 
     } 
     return View(_user); 
    } 

    public ActionResult Login() 
    { 
     LoginViewModel LVM = new LoginViewModel(); 
     HttpCookie existingCookie = Request.Cookies["UserName"]; 
     if (existingCookie != null) 
     { 
      LVM.UserName = existingCookie.Value; 
     } 

     return View(LVM); 
    } 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Login(LoginViewModel u) 
    { 
     if (ModelState.IsValid) 
     { 
      if (u.RememberMe==true) 
      { 
       HttpCookie existingCookie = Request.Cookies["UserName"]; 
       if (existingCookie != null) 
       { 

        existingCookie.Value = u.UserName; 
        existingCookie.Expires = DateTime.Now.AddHours(-20); 
       } 


       HttpCookie newCookie = new HttpCookie("UserName", u.UserName); 
       newCookie.Expires = DateTime.Today.AddMonths(12); 
       Response.Cookies.Add(newCookie); 
      } 
      var v = entities.Users.Where(a => a.UserName.Equals(u.UserName) && a.Password.Equals(u.Password)).FirstOrDefault(); 
      if (v != null) 
      { 
       System.Web.HttpContext.Current.Session["UserName"] = u.UserName; 
       return RedirectToAction("Index"); 
      } 

     } 
     return View(u); 
    } 

,這裏是的,他們應該去操作方法的樣本,其中一些是在不同的控制器但結果是所有的人都一樣:

[Authorize(Roles = CustomRoles.RegisteredUser)] 
    public ActionResult Orders(User U) 
    { 

     return View(); 
    } 

[Authorize(Roles = CustomRoles.Manager)] 
    public ActionResult Stock() 
    { 

     return View(entities.Cars.ToList()); 
    } 

發生的事情是我重定向回登錄方法,這是如果用戶沒有登錄什麼應該發生,但在用戶登錄並仍在開發中

回答

0

你正在嘗試實現表單授權,但正如我認爲你忘記了授權屬性使用HttpContext.User.IsInRole方法來檢測用戶是否可以訪問操作。要解決你的問題,你可以通過你的web.config配置窗體身份驗證或手動分配的HttpContext.User中通過的HttpModule或在Global.asax.cs中應用這樣的活動,例如:

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) 
    { 
     HttpContext context = ((HttpApplication)sender).Context; 
     HttpCookie existingCookie = Request.Cookies["UserName"];    
     if (existingCookie != null) { 
      context = new new GenericPrincipal(new GenericIdentity(existingCookie.Value), new string[]{"Admin", "Manager"}); 
     } 
    } 
+0

如何配置形式通過web.config進行身份驗證? – Muffinator

+0

https://msdn.microsoft.com/en-us/library/xdt4thhy.aspx – IamMan