2013-10-24 18 views
1

將[Authorize(Roles =「admin」)]放在視圖上,它在用戶重定向時起作用,但是,儘管它們已經登錄,但它們總是被重定向到登錄視圖。 我應該如何更改這是爲了進入一個錯誤頁面或類似的東西?MVC授權角色轉到登錄視圖?

+0

什麼時候該重定向發生? –

+0

嗯,我只是把控制器視圖上面的授權,我希望只提供給某些角色,所以無論何時該網址真的被訪問。目前去那條路線,而不是在角色返回登錄視圖? – user1166905

+0

可能的重複[如何在用戶不在授權角色中時提供未授權頁面?](http://stackoverflow.com/questions/2322366/how-do-i-serve-up-an-unauthorized -page-when-a-user-is-in-the-the-authorized-role- – CodeCaster

回答

1

,你可以創建一個這樣

public class CustomAuthorize : AuthorizeAttribute 
    { 

     protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
     { 
      if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
      { 
       base.HandleUnauthorizedRequest(filterContext); 
      } 
      else 
      { 
       filterContext.Result = new RedirectToRouteResult(new 
       RouteValueDictionary(new { controller = "Home", action = "UnAuthorized" })); 

      } 
     } 
    } 

定製的授權屬性,並使用它像這樣

[CustomAuthorize(Roles="admin")] 

希望這有助於

+0

我從字面上把我的答案同時作爲這個,但它基本上是我以後所以我會標記你的答案是正確的。 – user1166905

+0

出於興趣,你會推薦使用RedirectToRouteResult而不是RedirectResult?如果是這樣,爲什 – user1166905

+0

我不是專家,但由於硬編碼路徑,我在重新分解期間遇到'RedirectResult'問題。 –

0

而不是重複提供我所用代碼的問題:Prevent FormsAuthenticationModule of intercepting ASP.NET Web API responses並作相應修改:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
public class AuthorizeCustom : AuthorizeAttribute 
{ 
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     if (filterContext.HttpContext.Request.IsAuthenticated) 
     { 
      filterContext.Result = new RedirectResult("/Error/Unauthorized"); 
     } 
     else 
     { 
      if (filterContext.HttpContext.Request.IsAjaxRequest()) 
      { 
       filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; 
      } 
      base.HandleUnauthorizedRequest(filterContext); 
     } 
    } 
} 

然後,爲「/ Error/Unauthorized」路由創建一個視圖,並將屬性[Authorize]更改爲[AuthorizeCustom]。現在,未經授權的人員將被重定向爲按預期登錄,而不在角色中的人員將被重定向到自定義視圖。