Asp.net

授權屬性中的 UrlHelper 和 ViewContext

  • April 18, 2010

我有一個我無法解決的場景:

我正在為 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 有什麼想法嗎?

您可以覆蓋該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.ViewData並且filterContext.Controller.TempData應該在OnAuthorization方法內部工作。最後,如果你想使用一個UrlHelper(在這種情況下沒有必要,因為RedirectToRouteResult更好)你可以實例化它:

var urlHelper = new UrlHelper(filterContext.RequestContext);

引用自:https://stackoverflow.com/questions/2661405