Время сеанса не работает asp. net mvc - PullRequest
0 голосов
/ 18 марта 2020

Что я хочу, так это то, что в приложении, если пользователь ничего не делает в течение более 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);
    }

Ответы [ 2 ]

0 голосов
/ 18 марта 2020

Ты почти там. Посмотрите на ваш код 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");

Обратите внимание, что весь код выше не был проверен .

0 голосов
/ 18 марта 2020

Если вы пытаетесь проверить сеанс пользователя, то почему бы не использовать вместо него фильтр Authorized?

[Authorized]
public class AppController : Controller
{}

Здесь можно найти больше случаев использования: Атрибут Authorize в ASP. NET MVC

Обновление: Атрибут Authorized будет действовать так же, как ваш код:

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

т.е. проверяет сеанс и, если он потерян и будет перенаправлен на страницу входа.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...