简体   繁体   English

在ASP.NET MVC中处理会话超时

[英]Dealing with Session timeout in ASP.NET MVC

I am working on a MVC application and I have a requirement of dealing with errors and session timeouts by redirecting the user to different error pages based on few parameters in the query string. 我正在MVC应用程序上工作,并且我需要根据查询字符串中的几个参数将用户重定向到不同的错误页面,以处理错误和会话超时。

The issue I am facing is that i tried to implement this by saving the required parameters from querystring into a session and then redirecting to error pages. 我面临的问题是,我试图通过将所需的参数从querystring保存到会话中,然后重定向到错误页面来实现此目的。 But before every HttpGet and Post action in my controllers I am checking if session is active. 但是在我的控制器中执行每个HttpGet和Post操作之前,我正在检查会话是否处于活动状态。

So in case of a situation where session values are lost and not able to read them. 因此,在会话值丢失并且无法读取它们的情况下。

How can I implement this thing in any other way? 我该如何以其他方式实现此功能?

You need to check whether the session exists, has the fields you expect and is active. 您需要检查会话是否存在,具有您期望的字段并且处于活动状态。 If the session does not exist or does not have a fields you expect, then handle the case when the session does not exist yet/expired. 如果会话不存在或没有您期望的字段,请处理该会话尚不存在/已过期的情况。 If it is not active, then handle the case when the session is no longer active. 如果它不是活动的,则处理会话不再活动的情况。 If everything is ok, then handle the request normally. 如果一切正常,则可以正常处理该请求。 If the session expired, then handle it as expired. 如果会话已过期,则将其视为已过期。

to check about session, you can use an ActionFilter like this: 要检查会话,可以使用如下所示的ActionFilter:

public class SessionActiveFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var activeSession = Session["user"];
            if (activeSession == null)
                //Here, do a redirect

            base.OnActionExecuting(filterContext);
        }
    }

Also, you can use a third option to save the session, like Redis Cache http://blogs.msdn.com/b/webdev/archive/2014/05/12/announcing-asp-net-session-state-provider-for-redis-preview-release.aspx 此外,您可以使用第三个选项来保存会话,例如Redis Cache http://blogs.msdn.com/b/webdev/archive/2014/05/12/announcing-asp-net-session-state-provider- for-redis-preview-release.aspx

I know this is a dead story now. 我知道这是一个死故事。 But I post this answer for the new comers. 但是我将这个答案发布给新来者。 Please see the nice tutorial in codeproject about how to check session values in Action Filters. 请参阅在漂亮的教程CodeProject上有关如何在操作过滤器检查会话值。

In a dynamic web application, the session is crucial to hold the information of current logged in user identity/data. 在动态Web应用程序中,会话对于保存当前登录的用户身份/数据的信息至关重要。 So someone without authentication cannot have access to some Page or any ActionResult, to implement this kind of functionality, we need to check session exists (is not null) in every action which required authentication.So, the general method is as follows: 因此,未经身份验证的人无法访问某些Page或任何ActionResult,要实现这种功能,我们需要检查每个需要身份验证的操作中会话是否存在(不为null),因此一般方法如下:

[HttpGet] 
public ActionResult Home() 
{
     if(Session["ID"] == null)
         return RedirectToAction("Login","Home"); 
}

We have to check the above 2 statements each time and in each ActionResult, but it may cause 2 problems. 我们每次都必须在每个ActionResult中检查以上2条语句,但它可能会导致2个问题。

  1. Repeat Things : As per the good programming stranded, we don't have to repeat the things. 重复事情 :根据搁浅的良好编程,我们不必重复这些事情。 Create a module of common code and access it multiple times/repeatedly 创建通用代码模块并多次/重复访问
  2. Code missing : We have to write code multiple times so it might happen some time we forget to write code in some method or we missed it. 缺少代码 :我们必须多次编写代码,因此有可能在某些时候我们忘记以某种方法编写代码,或者错过了它。

How To Avoid? 如何避免?

The ASP.NET MVC provides a very great mechanism ie, Action Filters. ASP.NET MVC提供了一个非常好的机制,即动作筛选器。 An action filter is an attribute. 动作过滤器是一个属性。 You can apply most action filters to either an individual controller action or an entire controller. 您可以将大多数动作过滤器应用于单个控制器动作或整个控制器。 If you want to know more about action filter, please click here . 如果您想了解更多有关动作过滤器的信息,请单击此处

So we will create a custom Action Filter that handles session expiration and if session is null, redirect to Login Action. 因此,我们将创建一个自定义的操作筛选器来处理会话到期,如果session为null,则重定向到Login Action。

Create a new class in your project and copy the following code: 在您的项目中创建一个新类,并复制以下代码:

namespace YourNameSpace
{
    public class SessionTimeoutAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;
            if (HttpContext.Current.Session["ID"] == null)
            {
                filterContext.Result = new RedirectResult("~/Home/Login");
                return;
            }
            base.OnActionExecuting(filterContext);
        }
    }
}

Now our Action Filter is created and we are ready to use it. 现在,我们的动作筛选器已创建,我们可以使用它了。 The following code will show you how we can apply attribute to Action or to complete controller. 以下代码将向您展示如何将属性应用于Action或完成控制器。

Apply to Action 申请采取行动

[HttpGet]
[SessionTimeout]
public ActionResult MyProfile()
{
    return View();
}

Apply to Controller 适用于控制器

[SessionTimeout]
public class HomeController : Controller
{
}

Now all actions of Home Controller will check for session when hit with the help of Action Filter. 现在,在动作过滤器的帮助下,Home Controller的所有动作都将检查会话。 So we have reduced the code and repetitive things. 因此,我们减少了代码和重复的事情。 This is the benefits of Action Filters. 这就是动作过滤器的好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM