2016-09-15 38 views
0

我的MVC網頁當前使用Session變量進行身份驗證。我想嘗試一下,所以我可以使用一個自定義的AuthorizeAttribute,這樣我就可以用[CustomAuth]來裝飾控制器。您如何重定向到自定義AuthorizeAttribute的動作結果

當前RedirectToRouteResult帶我到「此頁面無法顯示」頁面。代碼打到第一個RedirectToRouteResult。

它不相同的,如果我使用RedirectResult

,我怎麼把它引導到登錄頁面我有嗎?

這是我customAuth

public class CustomAuth : AuthorizeAttribute 
{ 
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     if (filterContext.RequestContext.HttpContext.Session["isAuth"] != null) 
     { 
      if (!(bool)filterContext.RequestContext.HttpContext.Session["isAuth"]) 
      { 

       filterContext.Result = new RedirectToRouteResult(new 
        RouteValueDictionary(new { controller = "Base", action = "Login" })); 
      } 
     } 
     else 
     { 
      filterContext.Result = new RedirectToRouteResult(new 
       RouteValueDictionary(new { controller = "Base", action = "Login" })); 
     } 
    } 
} 

編輯---

我想使用而不必把這個每一個動作每一個控制器控制器和動作[customAuth]

if (Session["isAuth"] != null) 
     { 
      if (!(bool)Session["isAuth"]) 
      { 
       Session.Clear(); 
       return RedirectToAction("Login", "Base"); 
      } 
     } 
     else return RedirectToAction("Login", "Base"); 

有沒有辦法做到這一點與匿名身份驗證?

+0

的路徑是什麼,以你的登錄頁面? – Luke

+0

基地/登錄,如果我把_Login的行動,我需要http:// localhost:/ Base/_Login與資源無法找到頁面,這是預期的原因沒有_Login。但是,如果我把基地/登錄它不重定向它只顯示無法顯示頁面。 – user1314413

+0

您能夠成功導航到/ base/login嗎?另外,你的控制器實際上是否叫做'BaseController'? – Luke

回答

0

下面是我如何使用從HandleErrorAttribute派生的屬性進行操作。

只需將filterContent.Result分配給新的ViewResult以設置目標。如果你需要它們,別忘了其他屬性。

public class HandleUnauthorizedAttribute : HandleErrorAttribute 
{ 
    public override void OnException(ExceptionContext filterContext) 
    { 
     base.OnException(filterContext); 

     if (filterContext.Exception.GetType() != typeof (SecurityException)) return; 

     var controllerName = (string) filterContext.RouteData.Values["controller"]; 
     var actionName = (string) filterContext.RouteData.Values["action"]; 
     var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); 

     filterContext.Result = new ViewResult 
     { 
      ViewName = "Unauthorized", 
      ViewData = new ViewDataDictionary<HandleErrorInfo>(model), 
      TempData = filterContext.Controller.TempData 
     }; 
     filterContext.ExceptionHandled = true; 
     filterContext.HttpContext.Response.Clear(); 
     filterContext.HttpContext.Response.StatusCode = 403; 
     filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; 
    } 
} 

的我剛剛註冊它在FilterConfig.cs

public class FilterConfig 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     filters.Add(new HandleUnauthorizedAttribute()); 
    } 
} 
+0

你的控制器是用[HandleUnauthorizedAttribute]裝飾還是拋出那個自定義異常? – user1314413

+0

你使用的是什麼版本的mvc?我將mvc 5的註冊碼添加到答案中。這將在每個請求上放置過濾器。但如果你想,你可以放在控制器或動作上。 – Fran

+0

我認爲你很混淆認證和授權。如果您所做的只是檢查用戶是否已通過身份驗證,則可以在web.config中配置該用戶,並將未經身份驗證的用戶發送到登錄URL。 – Fran

相關問題