C# 检查用户是否在mvc4中第一次打开站点或会话是否过期
如果会话过期,我将使用以下代码重定向到登录页面:C# 检查用户是否在mvc4中第一次打开站点或会话是否过期,c#,asp.net-mvc-4,session,C#,Asp.net Mvc 4,Session,如果会话过期,我将使用以下代码重定向到登录页面: public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (HttpContext.Current.Session.Count == 0 || HttpContext.Current.Session["UserRole"] == null) { f
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
if (HttpContext.Current.Session.Count == 0 || HttpContext.Current.Session["UserRole"] == null)
{
filterContext.Controller.TempData["Error"] = "Your Session have expired. Please relogin again.";
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
//filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index_Partial", controller = "Home" }));
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
error = true,
message = "Your Session have expired. Please relogin again."
}
};
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 501;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
else
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Home" }));
}
}
使用上述代码,一切正常
问题:
用户打开我正在显示欢迎消息的站点,然后如果用户单击站点树状图中的任何项目,因为所有项目仅对经过身份验证的用户可用,则消息应为“请登录”,因为用户之前没有任何活动会话,但通过如上代码中的检查会话,我只能显示单个消息
“您的会话已过期。请重新登录。”
如果情况仍然不清楚,请告诉我
提前感谢。您应该使用cookie保存用户日志信息,使用会话检查当前用户是否应再次登录。如果cookie为null或为空,则显示“请登录”。可能您还需要创建自定义授权筛选器。但我不希望这样做cookies@Sunny如果你想在没有cookie的情况下完成这项工作,那么你必须实现某种服务器端记录(可能是IP地址,如果这足够的话),最后一次访问时间实际上是基于cookie的。正如Miika L所说,实现某种服务器端记录,但无法检查用户是否登录。