【问题标题】:Session TimeOut is not working asp.net mvc会话超时不工作 asp.net mvc
【发布时间】:2020-03-18 08:24:28
【问题描述】:

我想要的是,在一个应用程序中,如果用户超过 2 分钟没有做任何事情,我想将页面重定向到登录页面,说明会话已过期。 所以为此,我尝试了类似下面的方法

在我的 HomeController 中

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);
    }

【问题讨论】:

  • 你知道如果用户在你的页面上什么都不做,你的C#代码永远不会被执行,对吧?
  • @vasily.sib: 是的,但是剩余的空闲应该处理一些注销?
  • 我的意思是,你的SessionTimeoutAttributeTimeout 没有任何作用。如果您还没有会话,它只会重定向到登录。也许您应该在会话中存储LoginAt 值,并在您的SessionTimeoutAttribute 中检查此值?
  • @vasily.sib: 你能帮我写一些代码让我试试
  • 这取决于您如何登录您的用户?你有某种UsersController.Login() 行动吗?

标签: c# asp.net-mvc session-timeout


【解决方案1】:

你快到了。看你的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");

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

【讨论】:

  • 在哪里添加这行Session["UserLoginAt"] = DateTime.Now;
  • @nkb 就在//Session["isUserAuthenticated"] = result;下方
  • 正如我所说,"上面的代码没有被检查" :) 只是放一个分号
  • 什么都没有发生,伙计,如果你不介意的话,你可以过来聊天讨论一下吗
  • 你是他们的伴侣吗?
【解决方案2】:

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

[Authorized]
public class AppController : Controller
{}

更多用法可以在这里找到:Authorize attribute in ASP.NET MVC

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

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

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

【讨论】:

  • 在发布答案时强烈推荐一些有用的链接和代码
  • 我不想进行身份验证,我想处理超时功能。身份验证正在工作
猜你喜欢
  • 2014-12-13
  • 2011-08-12
  • 2016-07-11
  • 1970-01-01
  • 2011-04-12
  • 2015-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多