如果会话在 MVC 中不可用,如何重定向到登录页面
How to redirect to login page if session is not available in MVC
我正在开发 ASP.Net MVC 5.0 应用程序,.现在我已经创建了登录页面。当用户有效时,我将用户详细信息存储到 seesion 中。
if(_loginmodel.authstatus == false)
{
return View("Index");
}
Session["authstatus"] = true;
Session["userid"] = _loginmodel.userid;
Session["useremail"] = _loginmodel.useremail;
Session["username"] = _loginmodel.username;
否,当用户转到其他文件时,我再次检查会话是否可用
public class CityController : Controller
{
private CityModels _citymodel;
#region Constructor
public CityController()
{
if (Session != null && Session["authstatus"] != null)
{
_citymodel = new CityModels();
}
RedirectToAction("Index", "Login");
}
#endregion
}
所以现在如果会话过期我该如何将他重定向到登录页面
我想你可以将这个逻辑包装在一个动作过滤器中,并在那里重定向:
public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(FilterExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
Controller controller = filterContext.Controller as Controller;
if (controller != null)
{
if (session != null && session ["authstatus"] == null)
{
filterContext.Result =
new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "Login" },
{ "action", "Index" }
});
}
}
base.OnActionExecuting(filterContext);
}
}
此处有更多详细信息:
您应该创建一个自定义过滤器属性来处理会话过期,如下所示 -
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
/// <summary>
/// Custom attribute for handling session timeout
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
if (ctx.Session != null)
{
// check if a new session id was generated
if (ctx.Session.IsNewSession)
{
// If it says it is a new session, but an existing cookie exists, then it must
// have timed out
string sessionCookie = ctx.Request.Headers["Cookie"];
if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
{
ctx.Response.Redirect("~/Error/SessionTimeoutVeiw");
}
}
}
base.OnActionExecuting(filterContext);
}
}
现在要使用此自定义属性,请使用此属性装饰您的控制器方法或class。
[SessionExpireFilterAttribute]
如果您需要将此过滤器应用于所有控制器,您可以在 FilterConfig 文件中注册此过滤器。
因此,当会话过期时,作为会话中的值,您无需检查特定会话值是否已过期。
在 web.config 文件中写入代码以将会话超时设置为 2 分钟
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" timeout="1" />
</authentication>
<sessionState timeout="2"></sessionState>
<globalization uiCulture="en" culture="en-GB"/>
</system.web>
在 layout.cshtml
中的 <script>
标记中写入以下代码
//session end
var sessionTimeoutWarning = @Session.Timeout - 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location.hostname = "";
/* $(window.Location).attr("href", "@Url.Content("~/Login/index/")"); */
window.location = "/Login/index/";
}
在control和action中编写下面的代码
[HttpGet]
public ActionResult Logout()
{
Session["id1"] = null;
Session["id2"] = null;
Session["id3"] = null;
Session["id4"] = null;
Session["Region"] = null;
Session.Clear();
Session.RemoveAll();
Session.Abandon();
Response.AddHeader("Cache-control", "no-store, must-revalidate, private, no-cache");
Response.AddHeader("Pragma", "no-cache");
Response.AddHeader("Expires", "0");
Response.AppendToLog("window.location.reload();");
return RedirectToAction("Index", "Login");
}
您可以在全局
中的 Session_Start 事件中将用户重定向到登录页面
protected void Session_Start()
{
if (Session["Username"] != null)
{
//Redirect to Welcome Page if Session is not null
HttpContext.Current.Response.Redirect("~/WelcomeScreen", false);
}
else
{
//Redirect to Login Page if Session is null & Expires
new RedirectToRouteResult(new RouteValueDictionary { { "action", "Index" }, { "controller", "Login" } });
}
}
我正在开发 ASP.Net MVC 5.0 应用程序,.现在我已经创建了登录页面。当用户有效时,我将用户详细信息存储到 seesion 中。
if(_loginmodel.authstatus == false)
{
return View("Index");
}
Session["authstatus"] = true;
Session["userid"] = _loginmodel.userid;
Session["useremail"] = _loginmodel.useremail;
Session["username"] = _loginmodel.username;
否,当用户转到其他文件时,我再次检查会话是否可用
public class CityController : Controller
{
private CityModels _citymodel;
#region Constructor
public CityController()
{
if (Session != null && Session["authstatus"] != null)
{
_citymodel = new CityModels();
}
RedirectToAction("Index", "Login");
}
#endregion
}
所以现在如果会话过期我该如何将他重定向到登录页面
我想你可以将这个逻辑包装在一个动作过滤器中,并在那里重定向:
public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(FilterExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
Controller controller = filterContext.Controller as Controller;
if (controller != null)
{
if (session != null && session ["authstatus"] == null)
{
filterContext.Result =
new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "Login" },
{ "action", "Index" }
});
}
}
base.OnActionExecuting(filterContext);
}
}
此处有更多详细信息:
您应该创建一个自定义过滤器属性来处理会话过期,如下所示 -
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
/// <summary>
/// Custom attribute for handling session timeout
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
if (ctx.Session != null)
{
// check if a new session id was generated
if (ctx.Session.IsNewSession)
{
// If it says it is a new session, but an existing cookie exists, then it must
// have timed out
string sessionCookie = ctx.Request.Headers["Cookie"];
if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
{
ctx.Response.Redirect("~/Error/SessionTimeoutVeiw");
}
}
}
base.OnActionExecuting(filterContext);
}
}
现在要使用此自定义属性,请使用此属性装饰您的控制器方法或class。
[SessionExpireFilterAttribute]
如果您需要将此过滤器应用于所有控制器,您可以在 FilterConfig 文件中注册此过滤器。
因此,当会话过期时,作为会话中的值,您无需检查特定会话值是否已过期。
在 web.config 文件中写入代码以将会话超时设置为 2 分钟
<system.web> <compilation debug="true" targetFramework="4.0" /> <authentication mode="Forms"> <forms loginUrl="~/Login/Index" timeout="1" /> </authentication> <sessionState timeout="2"></sessionState> <globalization uiCulture="en" culture="en-GB"/> </system.web>
在 layout.cshtml
中的<script>
标记中写入以下代码//session end var sessionTimeoutWarning = @Session.Timeout - 1; var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000; setTimeout('SessionEnd()', sTimeout); function SessionEnd() { window.location.hostname = ""; /* $(window.Location).attr("href", "@Url.Content("~/Login/index/")"); */ window.location = "/Login/index/"; }
在control和action中编写下面的代码
[HttpGet] public ActionResult Logout() { Session["id1"] = null; Session["id2"] = null; Session["id3"] = null; Session["id4"] = null; Session["Region"] = null; Session.Clear(); Session.RemoveAll(); Session.Abandon(); Response.AddHeader("Cache-control", "no-store, must-revalidate, private, no-cache"); Response.AddHeader("Pragma", "no-cache"); Response.AddHeader("Expires", "0"); Response.AppendToLog("window.location.reload();"); return RedirectToAction("Index", "Login"); }
您可以在全局
中的 Session_Start 事件中将用户重定向到登录页面protected void Session_Start()
{
if (Session["Username"] != null)
{
//Redirect to Welcome Page if Session is not null
HttpContext.Current.Response.Redirect("~/WelcomeScreen", false);
}
else
{
//Redirect to Login Page if Session is null & Expires
new RedirectToRouteResult(new RouteValueDictionary { { "action", "Index" }, { "controller", "Login" } });
}
}