[Solved]-Cookie loses value when page is changed in MVC

[Solved]-Cookie loses value when page is changed in MVC

I’m working on Web application in which I have to implement remember me feature for that I decided to create a cookie for storing the username of the user.

Issue – When a user logs in to my Web Application, I create a cookie for storing the username of the user.But when the user redirects the page from logging in to another page, the cookie loses its value. I’m not getting the cookie value in another action method. Strange thing is that the cookie is still there but its value is empty.

I’ve double-checked my code and debug also to ensure that the cookie doesn’t get rewritten. After struggling for 1-2 hours in Google I find out the solution to the issue. So that I decided to write the solution that worked for me.

Point in the Post:

  • ASP.NET MVC Cookie gets deleted after redirect to action
  • Response.Cookies gets reset when RedirectToAction is called
  • Implement Remember Me with Login in ASP.Net MVC

    We just need to set the cookie. Secure property to false.

 HttpCookie _rememberme = new HttpCookie("_rememberme");
                    _rememberme.Expires = DateTime.Now.AddDays(30);
                    _rememberme["UserName"] = ac.UserName;
                    _rememberme["Password"] = ac.Password;
                    _rememberme.Secure = false; //this line of code is responsible for that
                    Response.Cookies.Add(_rememberme);

 

There are many types of files in our mobiles and laptops, out of which cookies are also a normal text file present in our hard drive which is automatically saved from the Internet.

Whenever we open a website, all its information is saved in a file so that whenever we open a website again, it is easier to open any page related to it, and thus we also take less time. And the data cost is also less.

If we talk technically, it works like a kind of identification card which is very important for advertising size and e-commerce websites on the internet because it is very effective to show all types of ads related to them.

Just as the names of their operating systems are placed on food items in Android mobiles, similarly the name of Internet Cookies is associated with a food item. So today we will tell you in this article what is cookies and how does it work and what are its benefits.

Ashok Patel

I'm a software engineer, having good experience in software programming web designing with great command on ASP.NET, React JS, Angular JS,.NET Core HTML5, JavaScript, T-SQL, JQuery.
Also have great experience in Electronics and electrical engineers design.
I like to do RND and Research.

Add comment

Your Header Sidebar area is currently empty. Hurry up and add some widgets.