2013-10-29 52 views
0

我有以下的類來實現自定義授權系統: -如何重定向我的行動過濾器類retrn視圖

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 
    public class CheckUserPermissionsAttribute : ActionFilterAttribute 
    { 
     Repository repository = new Repository(); 
     public string Model { get; set; } 
     public string Action { get; set; } 

     public override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      string ADusername = filterContext.HttpContext.User.Identity.Name.Substring(filterContext.HttpContext.User.Identity.Name.IndexOf("\\") + 1); 
      if (!repository.can(ADusername,Model,Action))   { 
       filterContext.Result = new HttpUnauthorizedResult("You cannot access this page"); 


      } 

      base.OnActionExecuting(filterContext); 
     } 
    } 

但當前訪問使用Firefox我的web應用程序時,如果filterContext.Result = new HttpUnauthorizedResult("You cannot access this page");再來用戶將不斷收到提示窗口,永遠輸入用戶名和密碼。那麼是否有辦法修改我的操作方法,以便不返回filterContext.Result = new HttpUnauthorizedResult("You cannot access this page");,而是返回顯示諸如「您無權執行此操作的權限..」等消息的視圖。 感謝

回答

1

你可以返回一個ViewResult

var viewResult = new ViewResult(); 
viewResult.ViewName = "~/Views/Errors/Unauthorized.cshtml"; 
filterContext.Result = viewResult; 

你當然可以設置這個觀點結果實例中的其他屬性,如佈局,如果需要通過視圖的可能視圖模型。

+0

感謝您的回覆,但我應該在哪裏添加此代碼;在If語句內或base.OnActionExecuting(filterContext)之後; ? –

+1

在你正在返回一個'HttpUnauthorizedResult'的if語句裏面。 –

相關問題