asp.net-mvc-4 – 会话到期后重定向到特定页面(MVC4)

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-4 – 会话到期后重定向到特定页面(MVC4)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
C#MVC4项目:当会话到期时,我想重定向到特定的页面.

经过一些研究,我在项目中将以下代码添加到Global.asax中:

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

当会话过期时,它将在Response.Redirect(“Home / Index”)行引发异常;说在这种情况下,响应不可用

这里有什么问题?

解决方法

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

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

这是覆盖ActionFilterAttribute的类.

  1. public class SessionExpireAttribute : ActionFilterAttribute
  2. {
  3. public override void OnActionExecuting(ActionExecutingContext filterContext)
  4. {
  5. HttpContext ctx = HttpContext.Current;
  6. // check sessions here
  7. if( HttpContext.Current.Session["username"] == null )
  8. {
  9. filterContext.Result = new RedirectResult("~/Home/Index");
  10. return;
  11. }
  12. base.OnActionExecuting(filterContext);
  13. }
  14. }

然后在操作中只需添加如下所示的属性

  1. [SessionExpire]
  2. public ActionResult Index()
  3. {
  4. return Index();
  5. }

或者只需添加一次属性

  1. [SessionExpire]
  2. public class HomeController : Controller
  3. {
  4. public ActionResult Index()
  5. {
  6. return Index();
  7. }
  8. }

猜你在找的asp.Net相关文章