从mvc 4 c中的global.asax重定向到控制器#

时间:2017-01-06 08:28:27

标签: c# asp.net-mvc-4

这是我在global.asax中的代码:

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

  void Session_OnEnd(object sender, EventArgs e)
    {
        //if (Session.IsNewSession)
        //Response.RedirectToRoute("logout", "Home");

        //RouteData routeData = new RouteData();
        //routeData.Values.Add("controller", "Home");
        //routeData.Values.Add("action", "logout");
        ////routeData.Values.Add("Summary", "Error");
        ////routeData.Values.Add("Description", ex.Message);
        //IController controller = new HomeController();
        //controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

        // HttpContext.Current.RewritePath("Home/logout");
        //Response.Redirect("~/Home/logout");

        //HttpContext.Current.Response.Redirect("~/Home/logout");  

    }

我想在一段时间(1分钟)后发生会话结束时重定向。 这是我的

web.config(<sessionState mode="InProc" timeout="1" />)

我尝试了很多代码......但是没有工作。 当Session_OnEnd发生时,我想重定向到Home controller。但是Session_OnEnd中的上述代码没有任何建议。 Session_OnEnd中发生的错误是:

: An exception of type 'System.NullReferenceException' occurred in MyZefer.UI.dll but was not handled in user code Additional information: Object reference not set to an instance of an object. Object reference not set to an instance of an object.

任何建议? 如何重定向到控制器???

1 个答案:

答案 0 :(得分:0)

HTTP协议是无状态的。这意味着只要用户请求页面(并且可能通过发送带有会话ID的cookie在会话中启动或继续),连接就会终止。

可能会在服务器上引发Session_OnEnd方法,但在该阶段没有客户端,即连接的浏览器,您可以重定向。因此,此方法仅在您希望对即将到期的会话进行某些服务器端清理时才有用。删除数据库记录。

我建议您使用JavaScript中的计时器同步服务器上的会话时间。该计时器可以在页面加载/加载时启动,并且在您发出另一个请求(即加载新页面)时显然会重置。当计时器(setTimeout())过期时,它会将用户重定向为windows.Location

另请参阅MSDN Documentation Session_OnEnd