我正在尝试自定义我的 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;
}
}
问题是当用户从该方法完成重定向后到达 Controller 中的某个操作方法时,我在此方法中存储在 Session 或 TempData 中的任何内容都会丢失。我检查了 Session.Keys/TempData.Keys 等。但是所有值都丢失了。 base.HandleUnauthorizedRequest(filterContext);
中可能发生了某些事情。但我想调用 base 很重要。
谁能告诉我这种行为的确切原因以及如何防止这种情况发生?
最佳答案
表单授权和 session 对于 IIS 来说是不同的概念。您可以获得授权,但您的 session 可能无效(例如尝试重新启动应用程序池)。
试试这个自定义属性:
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);
}
}
}
}
关于c# - 使用授权属性清除 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7594439/