2016-01-06 58 views
1

我是新來學習mvc中的過濾器。我在我的項目中創建了一個授權過濾器。授權過濾器不能在我的mvc項目中工作

的AccountController

public class AccountController : Controller 
    { 
     // 
     // GET: /Account/ 

     public ActionResult Login() 
     { 
      return View(); 
     } 
     [HttpPost] 
     public ActionResult Logins() 
     { 
      string username = Request["username"]; 
      string password = Request["password"]; 
      Session.Add("username", username); 
      Session.Add("password", password); 

      return Redirect("/Home"); 
     } 

    } 

    public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter 
    { 
     void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext) 
     { 
      try 
      { 
       string username = HttpContext.Current.Session["username"].ToString(); 
       string password = HttpContext.Current.Session["password"].ToString(); 

       if (username == password) 
       { 

        HttpContext.Current.Response.Redirect("/Home"); 

       } 
       else 
       { 

        HttpContext.Current.Response.Redirect("/Account/login"); 
       } 
      } 
      catch 
      { 
       HttpContext.Current.Response.Redirect("/Account/login"); 
      } 
     } 

    } 

的HomeController

public class HomeController : Controller 
    { 
     // 
     // GET: /Home/ 
     [CustomAuthorization] 
     public ActionResult Index() 
     { 

      return View(); 
     } 

    } 

但現在我檢查相同的字符串作爲用戶名和密碼,當我運行這個項目,如果用戶名和密碼是正確的主頁被一次又一次地重新加載。

+0

如果用戶名和密碼正確,那麼它會加載in由於您編寫HttpContext.Current.Response.Redirect(「/ Home」);因此,在homecontroller中執行dex(默認操作)操作。 –

+0

但它不去家裏索引。重定向循環中的主頁。 –

+0

這是故意的嗎? 'if(username == password)' – mbm

回答

1

從授權屬性,覆蓋默認行爲,繼承 簡單的實現方式是這樣的

public class OptionalAuthorizeAttribute : AuthorizeAttribute 
{ 

public OptionalAuthorizeAttribute() 
{ 

} 

protected override bool AuthorizeCore(HttpContext httpContext){ 
      string username = HttpContext.Current.Session["username"].ToString(); 
      string password = HttpContext.Current.Session["password"].ToString(); 

      if (username == password) 
      { 
       return true; 
      } 
       return base.AuthorizeCore(httpContext); 
    } 
} 

然後你就可以覆蓋AuthorizeAttribute.HandleUnauthorizedRequest的行爲(System.Web.Mvc.AuthorizationContext)

方注意:我是從手機上寫下這個答案的,所以請在粘貼到visual studio時仔細檢查語法錯誤