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);
可能有些事情正在发生。但我想这个调用基地很重要。
有人可以告诉我这种行为的确切原因,我该如何防止它发生?