Add a new persistent cookie using ASP.NET core

Viewed 1087

I am new to ASP.NET and trying to add a new cookie. I am using ASP.NET version 3.1.401 and in my homecontroller file I am trying to follow this: How to create persistent cookies in asp.net?. I have a using-statement using System.Web and within my homecontroller class I have a method which looks like:

public IActionResult Index()
{
    @ViewData["timezone"] = Convert.ToString(TimeZoneController.showTimeZone());
    @ViewData["ip"] = IPController.getIP();
    //create a cookie
    HttpCookie myCookie = new HttpCookie("myCookie");

    //Add key-values in the cookie
    myCookie.Values.Add("userid", "new_user");

    //set cookie expiry date-time. Made it to last for next 12 hours.
    myCookie.Expires = DateTime.Now.AddHours(12);

    //Most important, write the cookie to client.
    Response.Cookies.Add(myCookie);
    return View();
}

And I keep getting the following error:

CS1729: 'HomeController.HttpCookie' does not contain a constructor that takes 1 arguments

And

CS1061: 'HomeController.HttpCookie' does not contain a definition for 'Values' and no accessible extension method 'Values' accepting a first argument of type 'HomeController.HttpCookie' could be found (are you missing a using directive or an assembly reference?)

How can I get and set cookies and where should I do it within the MVC pattern?

2 Answers

I realized that my mistake was that I am developing on macos and as such I am using ASP.NET core NOT ASP.NET. It is a silly mistake, but I'm sure many beginners will make it. Here is a link on how to set cookies when you are using ASP.NET core.

Have you tried:

        //Add key-values in the cookie
        myCookie.Values["userid"] = "new_user";

That should work. Also make sure you're using HttpCookie from System.Web.

Related