MVC 检查 Session 变量,注销,全局重定向

MVC Check Session variable, sign out, and redirect globally

登录后,我为刚刚登录的用户保存一个 Session 变量。这个 Session 变量对于用户随后看到的每一件事都非常非常重要(参见这个问题

我发现存在一个潜在的问题,即 Session 变量与正在登录的用户无关,它有自己的到期时间(除非有人可以 100% 地证明这种情况不会发生,例如,当我重新开始调试时,我仍然登录但会话变量已经消失,无论是否过期)。

然后我要做的是检查 Session 变量是否存在,将它们注销并在其为空时重定向。然而,重定向需要在 Action 中完成,并且需要为每个 get 请求发生,因此会有很多重复代码。

var customerIdSession = Session["CustomerId"];
if (customerIdSession == null)
{
     // Then sign out which needs the AuthenticationManager property to be defined in the controller too!
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); 

     return RedirectToAction("Login", "Account");
}
var customerId = Convert.ToInt32(customerIdSession);

有什么办法可以解决这个问题吗?不必在每个 get 方法上都这样做。以某种方式使其成为全局检查,就像 Authorize 对 login

所做的那样

最后我自己找到了答案。我认为我的想法类似于 Authorize,因此找到了一种方法来制作我自己的 Authrorize 属性。这样,我可以将属性放在每个 Controller 之上,然后假设 Session 变量存在于每个操作中。如果没有,用户将自动注销并重定向。

public class AuthorizeSessionAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var customerId = httpContext.Session["CustomerId"];

        if (customerId == null)
        {
            var lo = httpContext.GetOwinContext().Authentication;
            lo.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

            return false;
        }

        return true;
    }
}