会话过期后重定向到特定页面 (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();
}
}