2011-09-29 99 views
1

我想自定義我的授權屬性,以便它將用戶重定向到適當的頁面,如果他沒有被授權。使用Authorize屬性清除會話?

這是我的代碼至今:

public class CustomAuthorizationAttribute : AuthorizeAttribute 
    { 
     public string ErrorMessage { get; set; } 

     public string WebConfigKey { get; set; } 

     private const string UnauthorizedAccessMessage = "UnauthorizedAccessMessage"; 


     protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
     { 
      HttpContext.Current.Session["foo"] = "bar"; 

      base.HandleUnauthorizedRequest(filterContext); 

      if (string.IsNullOrEmpty(WebConfigKey)) 
       throw new ArgumentNullException("WebConfigKey parameter is missing. WebConfigKey should give the actual page/url"); 

      string configValue = ConfigurationManager.AppSettings[WebConfigKey]; 

      if (string.IsNullOrEmpty(configValue)) 
       throw new Exception(WebConfigKey + "'s value is null or empty"); 

      if (!configValue.StartsWith("http")) 
       HttpContext.Current.Response.Redirect(WebUIUtils.GetSiteUrl() + configValue); 
      else 
       HttpContext.Current.Response.Redirect(configValue); 

      filterContext.Controller.TempData[UnauthorizedAccessMessage] = ErrorMessage; 

      HttpContext.Current.Session[UnauthorizedAccessMessage] = ErrorMessage; 

     } 
    } 

問題是,當用戶到達在一些操作方法,在控制器重定向從這個方法做後,無論我在Session或TempData的存儲在這個方法中丟失。我檢查了Session.Keys/TempData.Keys等,但所有的值都丟失了。 base.HandleUnauthorizedRequest(filterContext);可能有些事情正在發生。但我想這個調用基地很重要。

有人可以告訴我這種行爲的確切原因,我該如何防止它發生?

回答

1

表單授權和會話是IIS的不同概念。您可以被授權,但會話可能無效(例如嘗試重新啓動應用程序池)。

嘗試用這種自定義屬性:

public class CustomAuthorizationAttribute : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     base.OnAuthorization(filterContext); 
     if (filterContext.Result == null) 
     { 

      if (filterContext.HttpContext.Session != null) 
      { 
       //add checks for your configuration 
       //add session data 

       // if you have a url you can use RedirectResult 
       // in this example I use RedirectToRouteResult 

       RouteValueDictionary rd = new RouteValueDictionary(); 
       rd.Add("controller", "Account"); 
       rd.Add("action", "LogOn"); 
       filterContext.Result = new RedirectToRouteResult("Default", rd); 
      } 
     } 
    } 
}