当前位置: 首页 > 编程语言 > C#

在mvc4中的Global.asax中的会话超时重定向分享

时间:2023-04-10 14:07:14 C#

C#学习教程:mvc4中Global.asax中的会话超时重定向完成后将用户重定向到主页。我使用下面的代码,我在这里找到Global.asax中:];if((null!=sCookieHeader)&&(sCookieHeader.IndexOf("ASP.NET_SessionId")>=0)){//拦截当前路由HttpContextBasecurrentContext=newHttpContextWrapper(HttpContext.Current);RouteDatarouteData=RouteTable.Routes.GetRouteData(currentContext);//为区域替换路由数据令牌值routeData.DataTokens["area"]="";routeData.DataTokens["UseNamespaceFallback"]=true;//替换路由值routeData.Values["controller"]="home";routeData.Values["action"]="index";routeData.Values.Add("timedOut","true");//routeData.Values["id"]="timedOut";IRouteHandlerrouteHandler=routeData.RouteHandler;RequestContextrequestContext=newRequestContext(currentContext,routeData);IHttpHandlerhttpHandler=routeHandler.GetHttpHand勒(请求上下文);httpHandler.ProcessRequest(上下文);响应.Flush();响应.End();我认为这是正常的,因为它在开发环境中工作,但是当我在我的服务器上运行时在(IIS7)上尝试它时,我收到以下错误'HttpContext.SetSessionStateBehavior'canonlybecalledbefore'HttpApplication.AcquireRequestState'我已经使用此处的链接确定了问题,但我无法使其正常工作。我相信问题出在IHttpHandlerhttpHandler=routeHandler.GetHttpHandler(requestContext);下面httpHandler.ProcessRequest(上下文);但我似乎无法让它在服务器上运行。有什么想法或建议吗?您可以为您的控制器创建一个自定义操作过滤器来处理这个问题:usingSystem;使用System.Collections.Generic;使用System.Linq;使用System.Web;使用System.Web.Mvc;使用System.Reflection;命名空间Web{publicclassSessionExpireFilterAttribute:ActionFilterAttribute{publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext){HttpContextctx=HttpContext.Current;//检查是否支持会话if(ctx.Session!=null){//检查生成的if(ctx.Session.IsNewSession){//如果它说这是一个新会话,但存在一个现有的cookie,那么它必须//超时stringsessionCookie=ctx.Request.Headers["Cookie"];if((null!=sessionCookie)&&(sessionCookie.IndexOf("ASP.NET_SessionId")>=0)){ctx.Response.Redirect("~/Home/Login");}}}base.OnActionExecuting(filterContext);然后,我将把这个过滤器应用到我的Controller操作方法中,如下图:以上是C#学习教程:mvc4中Global.asax中的会话超时重定向。有用,需要了解更多C#学习教程,希望大家多多关注——usingSystem;使用System.Collections.Generic;使用System.Linq;使用System.Web;使用System.Web.Mvc;使用System.Web。Mvc.Ajax;namespaceWeb.Controllers{publicclassHomeController:Controller{[SessionExpireFilter]publicActionResultIndex(){//如果我们的会话已经过期,这个方法将不会执行//渲染主页returnView();}publicActionResultLogin(){//渲染登录页面returnView();}}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: