会话超时不适用于asp.net mvc



我想要的是,在应用程序中,如果用户在2分钟以上没有做任何事情,我想将页面重定向到登录页面,声明会话已过期。因此,我尝试了低于的方法

在我的家庭控制器

public class SessionTimeoutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{            
HttpContext ctx = HttpContext.Current;
var strSession = HttpContext.Current.Session;
if (strSession == null)
{
filterContext.Result = new RedirectResult("Login");                
}
base.OnActionExecuting(filterContext);
}
}

在每一种控制器方法中,我都添加了这样的

[SessionTimeout]
public class AppController : Controller
{}

下面也是这样

[HttpGet]
public ActionResult Assign()
{
string validUser = "";
string action = "";
string controller = "";
List<UMSLocationDetails> lstUMSLocationDetails = new List<UMSLocationDetails>();
HomeController homeController = new HomeController();
string assignUser = homeController.CheckRole(Convert.ToString(TempData["LoginUserName"]), Convert.ToString(TempData["strCurrentGroupName"]));
if (Convert.ToString(TempData["strCurrentGroupName"]) != assignUser || Convert.ToString(TempData["strCurrentGroupName"]) == "" || Convert.ToString(TempData["strCurrentGroupName"]) == null)
{
return RedirectToAction("Login", "Home");
}
else
{
if (TempData["Location"] != null)
{
lstUMSLocationDetails = TempData["Location"] as List<UMSLocationDetails>;
ViewBag.LocationDetails = lstUMSLocationDetails;
TempData.Keep();
//TempData.Remove("Location");
ViewBag.LoginUserName = Convert.ToString(TempData["LoginUserName"]);
//ViewBag.LoginUserName = Convert.ToString(Session["LoginUserName"]);  
ViewBag.CurrentGroupName = Convert.ToString(TempData["strCurrentGroupName"]).Replace("_", " ");
ViewBag.strReturnMessage = Convert.ToString(TempData["strReturnMessage"]);
TempData.Remove("strReturnMessage");
if (assignUser == strSapUserRole)
{
validUser = "";
action = "Assign"; controller = "App";
}
else
{
validUser = "1";
// return RedirectToAction("Login", "Home");
action = "Login"; controller = "Home";
}
//TempData.Remove("LoginUserName");
//TempData.Remove("strCurrentGroupName");
}
if (validUser == "1")
{
return RedirectToAction("Login", "Home");
}
else
{
return View();
}
}
}
[HttpGet]
public ActionResult Certify()
{
string validUser = "";
string action = "";
string controller = "";
List<UMSLocationDetails> lstUMSLocationDetails = new List<UMSLocationDetails>();
HomeController homeController = new HomeController();
string certifyUser = homeController.CheckRole(Convert.ToString(TempData["LoginUserName"]), Convert.ToString(TempData["strCurrentGroupName"]));
//  string certifyUser = "NEIQC_FIBER_ENGINEER";
if (Convert.ToString(TempData["strCurrentGroupName"]) != certifyUser || Convert.ToString(TempData["strCurrentGroupName"]) == "" || Convert.ToString(TempData["strCurrentGroupName"]) == null)
{
return RedirectToAction("Login", "Home");
}
else
{
if (TempData["Location"] != null)
{
lstUMSLocationDetails = TempData["Location"] as List<UMSLocationDetails>;
ViewBag.LocationDetails = lstUMSLocationDetails;
TempData.Keep();
//TempData.Remove("Location");
ViewBag.LoginUserName = Convert.ToString(TempData["LoginUserName"]);
ViewBag.CurrentGroupName = Convert.ToString(TempData["strCurrentGroupName"]).Replace("_", " ");
TempData.Keep();
if (certifyUser == strFEUserRole)
{
validUser = "";
action = "Certify"; controller = "App";
}
else
{
validUser = "1";
// return RedirectToAction("Login", "Home");
action = "Login"; controller = "Home";
}
}
if (validUser == "1")
{
return RedirectToAction("Login", "Home");
}
else
{
return View();
}
// return View();
// return RedirectToAction(action, controller);
}
}
[HttpGet]
public ActionResult Approver()
{
string validUser = "";
string action = "";
string controller = "";
List<UMSLocationDetails> lstUMSLocationDetails = new List<UMSLocationDetails>();
HomeController homeController = new HomeController();
string aprroverUser = homeController.CheckRole(Convert.ToString(TempData["LoginUserName"]), Convert.ToString(TempData["strCurrentGroupName"]));
if (Convert.ToString(TempData["strCurrentGroupName"]) != aprroverUser || Convert.ToString(TempData["strCurrentGroupName"]) == "" || Convert.ToString(TempData["strCurrentGroupName"]) == null)
{
return RedirectToAction("Login", "Home");
}
else
{

if (TempData["Location"] != null)
{
lstUMSLocationDetails = TempData["Location"] as List<UMSLocationDetails>;
ViewBag.LocationDetails = lstUMSLocationDetails;
TempData.Keep();
//TempData.Remove("Location");
ViewBag.LoginUserName = Convert.ToString(TempData["LoginUserName"]);
ViewBag.CurrentGroupName = Convert.ToString(TempData["strCurrentGroupName"]).Replace("_", " ");
if (aprroverUser == strCMMpUserRole)
{
validUser = "";
action = "Certify"; controller = "App";
}
else
{
validUser = "1";
// return RedirectToAction("Login", "Home");
action = "Login"; controller = "Home";
}
}
if (validUser == "1")
{
return RedirectToAction("Login", "Home");
}
else
{
return View();
}
// return View();
// return RedirectToAction(action, controller);
}
}

我尝试了上面的代码,但什么也没发生。请提出实现这一目标的最佳方式。

更新

[HttpPost]
[ValidateInput(false)]
public ActionResult ValidateUser()
{
string strUsername = Sanitizer.GetSafeHtmlFragment(Convert.ToString(Request.Form["txtUsername"]));
string strPassword = Sanitizer.GetSafeHtmlFragment(Convert.ToString(Request.Form["txtPassword"]));            
string strDbError = string.Empty;
strUsername = strUsername.Trim();
strPassword = strPassword.Trim();
string strUserName = "";
string strCurrentGroupName = "";
int intCurrentGroupID = 0;
string controller = "";
string action = "";
UserProviderClient ObjUMS = new UserProviderClient();
bool result = false;            
if (strUsername != "" || strPassword != "")
{
result = ObjUMS.AuthenticateUser(strUsername, strPassword, out strDbError);
try
{
if (result == true)
{
UMS ObjUMSDATA = new UMS();
//strUserName = System.Web.HttpContext.Current.User.Identity.Name.Split('\')[1];
strUserName = strUsername;
_UMSUserName = strUserName;
if (!string.IsNullOrEmpty(strUserName))
{
List<UMSGroupDetails> lstUMSGroupDetails = null;
List<UMSLocationDetails> lstUMSLocationDetails = null;
ObjUMSDATA.GetUMSGroups(strUserName, out strCurrentGroupName, out intCurrentGroupID, out lstUMSLocationDetails, out lstUMSGroupDetails);
if (strCurrentGroupName != "" && intCurrentGroupID != 0)
{
ViewBag.LoginUserName = strUserName.ToUpper();
ViewBag.CurrentGroupName = strCurrentGroupName;
ViewBag.CurrentGroupID = intCurrentGroupID;
ViewBag.GroupDetails = lstUMSGroupDetails;
ViewBag.LocationDetails = lstUMSLocationDetails;
TempData["LoginUserName"] = strUsername.ToUpper();
TempData["Location"] = lstUMSLocationDetails;
TempData["strCurrentGroupName"] = strCurrentGroupName;
TempData.Keep();
}
else
{
ModelState.AddModelError(string.Empty, "You are not registered. Please register first.");
return View("Login");
}
}
}
if (strCurrentGroupName == "SAP Executive")
{
action = "Assign"; controller = "App";
}
else if (strCurrentGroupName == "Maintenance Lead")
{
//return RedirectToAction("App", "Certify");
action = "Certify"; controller = "App";
}
else if (strCurrentGroupName == "NEIQC CMM")
{
//return RedirectToAction("App", "Approver");
action = "Approver"; controller = "App";
}
else
{
ModelState.AddModelError(string.Empty, "Invalid Username and password");                        
return View("Login");                        
}
}
catch (Exception ex)
{   
ApplicationLog.Error("Error", "ValidateUser", ex.Message);
}
}
else
{
ModelState.AddModelError(string.Empty, "Invalid Username and password");                
return View("Login");
}
//Session["isUserAuthenticated"] = result;            
return RedirectToActionPermanent(action, controller);
}

你差不多到了。看看你的ValidateUser()代码,末尾有一行注释:

//Session["isUserAuthenticated"] = result;

这就是您在会话中存储某些数据的方式。在评论下面加上这一行:

Session["UserLoginAt"] = DateTime.Now;

然后,在SessionTimeoutAttribute中,您需要获得以下值:

var timeout = TimeSpan.FromMinutes(2) // lets say you have a 2 minutes timeout
var userLoginAt = filterContext.HttpContext.Session["UserLoginAt"] as DateTime?;
if (userLoginAt.HasValue && userLoginAt.Value < DateTime.Now.Subtract(timeout))
// redirect to logOUT page if we are timed out
filterContext.Result = new RedirectResult("Logout");

请注意,以上所有代码均未检查。

如果您正在尝试检查用户会话,那么为什么不使用Authorized过滤器呢?

[Authorized]
public class AppController : Controller
{}

更多用法可以在这里找到:ASP.NET MVC 中的Authorize属性

更新:Authorized属性的作用与您的代码相同:

var strSession = HttpContext.Current.Session;
if (strSession == null)
{
filterContext.Result = new RedirectResult("Login");                
}

即检查会话,并且如果会话丢失则将重定向到登录页面。

最新更新