7

裏面我有一個場景,我一直沒能解決:UrlHelper和ViewContext的授權屬性

我與創造MVC自己的自定義授權屬性玩弄周圍。我想添加的主要功能是能夠更改用戶重定向到的位置,如果它們不在特定角色中。如果他們沒有通過身份驗證,我不介意系統將他們發送回登錄頁面,但是我想選擇發送他們的位置,但不允許他們訪問該操作方法。

這裏就是我想怎樣做:

public class CustomAuthorizeAttribute : AuthorizeAttribute 
{ 
     public string Action; 
     public string Controller; 

     protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) 
     { 
      // if User is authenticated but not in the correct role 
      string url = Url.Action(this.Action, this.Controller);     
      httpContext.Response.Redirect(url); 
     } 
    } 

而作爲一個額外的好處,我想有機會獲得ViewContext和TempData的我做的重定向之前。

有關如何在屬性中實例化UrlHelper和ViewContext的想法?

回答

11

您可以覆蓋OnAuthorization方法:

public override void OnAuthorization(AuthorizationContext filterContext) 
{ 
    if (filterContext == null) 
    { 
     throw new ArgumentNullException("filterContext"); 
    } 

    // Call the AuthorizeCore which should return true or false 
    if (!this.AuthorizeCore(filterContext.HttpContext)) 
    { 
     filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary() 
     { 
      { "controller", "home" }, 
      { "action", "about" }, 
      { "id", "foo" }, 
     }); 
    } 
} 

至於的ViewData和TempData的關注:filterContext.Controller.ViewDatafilterContext.Controller.TempDataOnAuthorization方法裏面工作。最後,如果你希望使用UrlHelper(在這種情況下沒有必要,因爲RedirectToRouteResult越好),你可以實例化它:

var urlHelper = new UrlHelper(filterContext.RequestContext); 
+1

輝煌,THX。看完你的迴應後,我意識到我可以簡單地問:「我如何獲得AuthorizationContext」。一旦我有,我很危險。 – 2010-04-18 21:32:44

+0

注意:實現OnAuthorization()方法並不是一件簡單的事情。如果您選擇重寫OnAuthorization()而不是AuthorizeCore(),請在OnAuthorization()中添加代碼以禁用或掛鉤輸出緩存。有關更多信息,請參閱http://forums.asp.net/p/1533590/3737756.aspx。 – Levi 2010-04-18 23:31:24