MVC检查会话变量,注销和全局重定向

时间:2016-03-16 12:30:24

标签: c# asp.net-mvc model-view-controller asp.net-identity

登录后,我正在为刚刚登录的用户保存一个Session变量。这个Session变量对于用户看到的每一件事都非常重要(参见这个问题MVC Individual User Accounts login value persisting

我发现存在一个潜在的问题,即Session变量与登录的用户没有关系,它有自己的到期时间(除非有人可以提供100%的傻瓜证明方式,例如,当我重新启动调试,我仍然登录但会话变量已经消失,无论是否到期)。

我所做的是检查Session变量是否存在,并将其签出并重定向,如果它为null。但是,重定向需要在Action中完成,并且需要在每次获取请求时发生,因此会有很多重复的代码。

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 for login

1 个答案:

答案 0 :(得分:1)

我最终找到了自己的答案。我认为它与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;
    }
}