2011-09-29 95 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); 
      } 
     } 
    } 
}