2010-10-07 100 views
2

如果不符合某些條件(例如HttpContext.Current.Request.Form [「key」]。toString()),我希望鎖定對html頁面的訪問(例如./manual/manual_A/index.html) 。 .Equals(「a」)),我希望重定向到特定的視圖(例如./errorPage/),否則繼續(例如/ index)。 In register Route I add:如何限制對ASP.NET MVC中某些頁面的訪問?

routes.MapRoute(
       "ErrorPage",            
       "errorPage/",       
       new { controller = "Home", action = "ErrorPage" } 
      ); 

routes.MapRoute(
       "Path",            
       "{*_request}",       
       new { controller = "Home", action = "Index" } 
      ); 

用於讀取所有請求。 在控制器首頁

[CustomAuthorize] 
    public ActionResult Index() 
    { 

    } 

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if(!condition) 
      filterContext.Result = RedirectToAction("PageError"); 
    } 

OnActionExecuting執行每個請求,然而,RedirectToAction不會發生。 任何提示我做錯了什麼?

+1

你redirectToAction和你的路由的行動不匹配,你可能也想檢查一下(PageError!= ErrorPage) – Tommy 2010-10-07 13:50:32

+1

你是否絕對肯定你的條件正在評估爲false?你可以在調試器下驗證它嗎?另請記住,授權在其他操作過濾器之前發生。如果您的[CustomAuthorize]掛鉤了OnAuthorization,您可能實際上希望從該過濾器中設置Result,而不是使用單獨的操作過濾器執行此操作。 – Levi 2010-10-07 16:54:52

+0

嗨,我找到了解決我的問題。在白天把代碼提供。感謝大家的建議。 – user468451 2010-10-08 04:36:08

回答

0

您需要設置filterContext.Result(如下所示),然後重定向到您的錯誤頁面。

filterContext.Result = new EmptyResult(); 
RedirectToAction("PageError"); 

這應該解決問題。

+0

爲什麼反對投票?我不告訴如何限制訪問。我的回答是如何停止操作並重定向到其他頁面。 – Pradeep 2010-10-07 07:29:23

+0

Pradeep - 你的回答是不正確的。在MVC中,諸如RedirectToAction()和其他產生ActionResult的工廠等方法沒有類似重定向的副作用。要從過濾器中執行重定向,可以將Result屬性設置爲原始海報完成後的RedirectResult或RedirectToRouteResult實例。 – Levi 2010-10-07 16:51:06

0

這是我的解決方案。 在Globax.asax:

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.RouteExistingFiles = true; 
    routes.MapRoute("PageError", "PageError/", new { controller = "Home", action = "PageError" }); 
    routes.MapRoute("PathPageStatic", "PathPageStatic/", new { controller = "Home", action = "PathPageStatic" }); 
    routes.MapRoute("Path", "{*_request}", new { controller = "Home", action = "Index"}); 
} 

在控制器中,我使用一個會話內存的條件:

public ActionResult PathPageStatic() 
{ 
    if (condition) 
    { 
    Session["key"] = condition; 
    return View("Index"); 
    } 
    else 
    return RedirectToRoute("PageError"); 
} 

[UserAuthorize] 
public ActionResult Index() 
{ 
    string patternStaticFile = @"\.*.(htm|html)"; 
    if (Regex.IsMatch(HttpContext.Request.Url.AbsoluteUri, patternStaticFile)) 
    { 
     string pathFile = HttpContext.Request.Url.LocalPath; 
     if (System.IO.File.Exists(pathFile)) 
     return new FilePathResult(pathFile, MimeType(pathFile)); 
     else return null; 
    } 
    else 
     return View(); 
} 

public ActionResult PageError() 
{ 
    return View("PageError"); 
} 

在AuthorizeAttribute:

public override void OnAuthorization(AuthorizationContext filterContext) 
{ 
    if (HttpContext.Current.Session["key"] == null) 
     filterContext.HttpContext.Response.Redirect("~/PageError", true); 
} 
相關問題