C# MVC全局检查会话变量、注销和重定向
登录时,我正在为刚刚登录的用户保存会话变量。这个会话变量对于用户看到的每一件事情都非常重要(参见这个问题) 我发现存在一个潜在的问题,即会话变量没有与登录的用户绑定,它有自己的到期日(除非有人能够提供100%的傻瓜式证明,例如,当我重新启动调试时,我仍然登录,但会话变量已不存在,无论到期日如何) 然后,我要做的是检查会话变量是否存在,并将其注销,如果为null,则重定向。但是,重定向需要在操作中完成,并且需要对每个get请求进行重定向,因此会有大量重复代码C# MVC全局检查会话变量、注销和重定向,c#,asp.net-mvc,model-view-controller,asp.net-identity,C#,Asp.net Mvc,Model View Controller,Asp.net Identity,登录时,我正在为刚刚登录的用户保存会话变量。这个会话变量对于用户看到的每一件事情都非常重要(参见这个问题) 我发现存在一个潜在的问题,即会话变量没有与登录的用户绑定,它有自己的到期日(除非有人能够提供100%的傻瓜式证明,例如,当我重新启动调试时,我仍然登录,但会话变量已不存在,无论到期日如何) 然后,我要做的是检查会话变量是否存在,并将其注销,如果为null,则重定向。但是,重定向需要在操作中完成,并且需要对每个get请求进行重定向,因此会有大量重复代码 var customerIdSessi
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类似,因此找到了一种方法来创建自己的Authorize属性。这样,我可以将属性置于每个控制器之上,然后假设会话变量存在于每个操作中。否则,用户将自动注销并重定向
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;
}
}