2011-12-22 77 views
1

我完全沉迷於此。基本上,我有一個自定義的AuthorizeAttribute的MVC頁面,如果用戶通過身份驗證但會導致403錯誤,但沒有適當的訪問權限。我遇到的問題是我想將此錯誤重定向到自定義控制器/操作(/ Error/Unauthorized)。IIS7.5 HttpErrors ExecuteURL不執行

我已經加入在我的web.config

<httpErrors errorMode="Custom"> 
    <remove statusCode ="403" subStatusCode="-1"/> 
    <error statusCode="403" path="/Error/Unauthorized" responseMode="ExecuteURL" /> 
</httpErrors> 

通過上述配置下面,我沒有看到默認的IIS 7.5 403重定向。但是,我也沒有看到任何東西。在IE中,它告訴我,該網站需要你登錄和鉻只是給我一個空白頁面。

任何想法?

這裏是情況自定義授權代碼,這可能有助於

public class CustomAuthorize : AuthorizeAttribute 
    { 
     //Property to allow array instead of single string. 
     private string[] _authorizedRoles; 

     public string[] AuthorizedRoles 
     { 
      get { return _authorizedRoles ?? new string[0]; } 
      set { _authorizedRoles = value; } 
     } 

     protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
     { 
      base.HandleUnauthorizedRequest(filterContext); 
      if (filterContext.HttpContext.Request.IsAuthenticated) 
      { 
       filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; 
       filterContext.Result = new HttpStatusCodeResult(403); 
      } 
     } 

     protected override bool AuthorizeCore(HttpContextBase httpContext) 
     { 
      if (httpContext == null) 
       throw new ArgumentNullException("httpContext"); 

      if (!httpContext.User.Identity.IsAuthenticated) 
       return false; 

      //Check to see if any of the authorized roles fits into any assigned roles only if roles have been supplied. 
      if (AuthorizedRoles.Any(httpContext.User.IsInRole)) 
       return true; 

      return false; 
     } 
    } 
+0

OK,只是想玩弄一些不同的情況,我說我的customErrors節到system.web節,並用404試過這種在這種情況下,(由於TrySkipIisCustomErrors我認爲),我發現我甚至不需要httpErrors部分。但是,如果我嘗試添加403,該頁面仍然無法解析。這只是瀏覽器如何解讀403?他們不會允許403被重定向嗎? – 2011-12-22 20:26:22

回答

0

OK,我不知道這是否是真正的正確與否,但它適合我的症狀。 http://forums.asp.net/t/1462153.aspx/1 我不高興我必須編寫重定向代碼,但我試圖使其至少明確爲未來的可維護性。

public bool RedirectAuthenticatedButUnauthorizedUsers { get; set; } 

    private String _redirectUnauthorizedUrl = String.Empty; 
    public String RedirectUnauthorizedUrl 
    { 
     get { return _redirectUnauthorizedUrl; } 
     set { _redirectUnauthorizedUrl = value.Trim(); } 
    } 

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     base.HandleUnauthorizedRequest(filterContext); 
     if (!RedirectAuthenticatedButUnauthorizedUsers || !filterContext.HttpContext.Request.IsAuthenticated) 
      return; 
     if(RedirectUnauthorizedUrl == String.Empty) 
      throw new NullReferenceException("RedirectAuthenticatedButUnauthorizedUsers " + 
              "set to true, but no redirect URL set."); 
     filterContext.HttpContext.Response.Redirect(RedirectUnauthorizedUrl); 
    } 
相關問題