Home > Enterprise >  How to get cookies time and perform autologin
How to get cookies time and perform autologin

Time:09-28

I am working on a DOT NET Core project in which I have to perform the task of auto-login. I have tried several ways but did not find the solution.

[HttpPost]
public async Task<IActionResult> IndexAsync(myLoginModel lm){
if (lm.IsRemember)
{
CookieOptions option = new CookieOptions();
option.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Append("UserEmail", lm.Email, option);
Response.Cookies.Append("UserPassword", lm.Password, option);
Response.Cookies.Append("IsRemember", lm.IsRemember.ToString(), option);
}
}

Now during 10-days if the user opens the website, I want to redirect to the DASHBOARD PAGE Directly.

public IActionResult Index()
{
string IsRemember= Request.Cookies["IsRemember"];
if (IsRemember== "True")
{
lm.Email = Request.Cookies["UserEmail"];
lm.Password = Request.Cookies["UserPassword"];
 //Check if user visited the website during 10 days of time then redirect to DASHBOARD PAGE.        
}
}

I have tried many ways in which the below code is one of them but did not get the perfect solution.

Tried Way 1

 foreach (HttpCookie thisCookie in this.Request.Cookies)
{
if (thisCookie.Expires < DateTime.Now)
{
// expired
}
}

Tried Way 2

if (Request.Cookies["UserEmail"].Expires.ToString() < DateTime.Now) 
{ 
                    
}

CodePudding user response:

You can not read the cookies expiration date. Please refer: (c# Asp.net getting Cookie expiration time set in javascript always returns 01.01.0001)

So you need to change your approach like following way.

Add Remember Time in Cookies.

Response.Cookies.Append("RememberTime", DateTime.Now(), option);

And read this RememberTime Cookies value and write your logic for check with as per you requirement day.

if (Convert.ToDateTime(Request.Cookies["RememberTime"]).AddDays(10) > DateTime.Now) 
  • Related