重定向到指定页面会话过期后

重定向到指定页面会话过期后

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

问题描述

C#MVC4项目:我想重定向到一个特定的页面,当会话过期

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

经过一番研究,我增加了以下code到的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(首页/索引)抛出一个异常; 响应不在这种情况下可用

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最简单的方法是,
在会话的情况下到期,你必须检查其会议的每一个动作,如果它为null,则重定向到索引页。

The easiest way in MVC is thatIn 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();
}

或者只需添加属性只是一次为:

Or Just add attribute only one time as :

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

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

08-21 11:15