会话过期后重定向到特定页面 (MVC4) [英] Redirect to specific page after session expires (MVC4)

查看:28
本文介绍了会话过期后重定向到特定页面 (MVC4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# MVC4 项目:我想在会话过期时重定向到特定页面.

C# MVC4 project: I want to redirect to a specific page when the session expires.

经过一番研究,我在我的项目中的 Global.asax 中添加了以下代码:

After some research, I added the following code to the Global.asax in my project:

protected void Session_End(object sender, EventArgs e)
{
     Response.Redirect("Home/Index");
}

当会话过期时,它会在 Response.Redirect("Home/Index"); 行抛出异常,说 响应在此上下文中不可用

When the session expires, it throws an exception at the line Response.Redirect("Home/Index"); saying The response is not available in this context

这里出了什么问题?

推荐答案

MVC 中最简单的方法是在会话过期的情况下,在每个操作中您都必须检查其会话,如果它为空,则重定向到索引页面.

The easiest way in MVC is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Index page.

为此,您可以创建自定义属性,如下所示:-

For this purpose you can make a custom attribute as shown :-

这是覆盖 ActionFilterAttribute 的类.

Here is the Class which overrides ActionFilterAttribute.

public class SessionExpireAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;
            // check  sessions here
            if( HttpContext.Current.Session["username"] == null ) 
            {
               filterContext.Result = new RedirectResult("~/Home/Index");
               return;
            }
            base.OnActionExecuting(filterContext);
        }
    }

然后在操作中添加此属性,如下所示:

Then in action just add this attribute as shown :

[SessionExpire]
public ActionResult Index()
{
     return Index();
}

或者只添加一次属性:

[SessionExpire]
public class HomeController : Controller
{
  public ActionResult Index()
  {
     return Index();
  }
}

这篇关于会话过期后重定向到特定页面 (MVC4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆