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

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

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

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

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

这里有什么问题?

解决方法

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

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

这是覆盖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);
        }
    }

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

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

或者只需添加一次属性:

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....