2014-05-09 50 views
2

在MVC5中是否有一個屬性會允許我拒絕授權用戶訪問某些頁面?MVC與[Authorize]相反,也許類似[DenyAuthorized] ..?

我試圖限制授權用戶查看某些頁面,如註冊頁面。

當前用戶可以瀏覽我的註冊頁面,如果他們知道URL即使他們註冊。

我以爲會有一個屬性,如[DenyAuthorized],或者是否有另一種方法來做到這一點?

我認爲這是一個相當普遍的要求,我可能沒有正確實施。

我寫了一個簡短的屬性和它的工作,但我不認爲這是做到這一點的最好辦法:

public class DenyAuthorized : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     if (filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      if (filterContext.HttpContext.Request.UrlReferrer != null) 
      { 
       filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.AbsoluteUri); 
      } 
      else 
      { 
       filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Home", area = "", })); 
      } 
     } 
    } 
} 

是否有更好的方法來做到這一點?

+0

我會使用這樣的屬性。我看到你正在檢查用戶是否被授權。如果他們是,拒絕他們或重定向他們。 – Chris

+0

[Here](http://stackoverflow.com/questions/238437/why-does-authorizeattribute-redirect-to-the-login-page-for-authentication-and-au)是一種替代方案。這個優點是隻有一個屬性來驗證和否認 – LostInComputer

回答

2

做的最好的方法是檢查用戶的登錄狀態的登錄/註冊行爲,並將其重定向到儀表板/主頁/登錄頁面,如果用戶已經簽署。

這是應該的。