Create Persistent Cookie in ASP.Net MVC

Last Reply 5 months ago By dharmendr

Posted 5 months ago

Hello Everyone,

I am facing issue with saving persistent cookie for 30 days, when i am creating cookie it is creating successfully but when i logout of my application or close the browser window, cookie is cleared off and cannot use anymore.

if (Request.Browser.Cookies)
{
    if (!string.IsNullOrEmpty(MachineName))
    {
        HttpCookie reqCookies = Request.Cookies["UserInfo"];
        if (reqCookies != null)
        {
            MachineName = reqCookies["MachineName"].ToString();
        }
    }
}

 

HttpCookie reqCookies = Request.Cookies["UserInfo"];
if (reqCookies == null)
{
    HttpCookie UserInfo = new HttpCookie("UserInfo");
    UserInfo["MachineName"] = MachineName[0];
    UserInfo.Expires.AddDays(30);
    //Response.Cookies.Add(UserInfo);
    HttpContext.Response.SetCookie(UserInfo);
}

Any help is Appreciated!

Posted 5 months ago

Hi vijay9471,

Response.SetCookie - Updates an existing cookie in the cookie collection.

Response.Cookies.Add - Adds the specified cookie to the cookie collection.

Instead of SetCookie method you need to use Cookies.Add method to add the Cookie to Browser.

Refer below article for more details.

ASP.Net Cookies: Read, Write (Save) and Remove (Delete) Cookies in ASP.Net using C# and VB.Net