Home > database >  Add Collection of Cookie in ASP.NET MVC
Add Collection of Cookie in ASP.NET MVC

Time:04-13

How can I add collection of cookies in ASP.NET MVC?

Normally, I use this code:

    [HttpPost]
    public ActionResult AddCookie()
    {
        Response.Cookies["Profile"]["Test1"] = "Something1";
        Response.Cookies["Profile"]["Test2"] = "Something2";
        Response.Cookies["Profile"]["Test3"] = "Something3";
        return RedirectToAction("Index", "Home");
    }

but is there any faster way for this?

For example using NameValueCollection:

        var nv = new NameValueCollection();
        nv["Test1"] = "Something1";
        nv["Test2"] = "Something2";
        nv["Test3"] = "Something3";
        // add Profile cookie here with nv values

CodePudding user response:

You can use JSON instead of different Key Values:

Say you have a FooStorage class as per below:

public class FooStorage
{
    public int SomeInteger { get; set; }
    public string? SomeString { get; set; }
    public List<string>? SomeMoreString { get; set; }
}

Now you can store any data you need (Which you should consider security too) in an instance of the class mentioned above.

For example:

var fooAsJSON = JsonSerializer.Serialize(new FooStorage
{
    SomeInteger = 1,
    SomeString = "Foo",
    SomeMoreString = new List<string>
    {
        "Foo1","Foo2","Foo3","a Long Long Long Foo",
    }
});

// Store your fooAsJSON in the cookie and then use it.

var another = JsonSerializer.Deserialize<FooStorage>(fooAsJSON);

However, when it comes to security, you shouldn't put a lot of trust in cookies. It is simple for the consumer to change and manipulate cookies, and you probably don't want to charge any significant infrastructure costs on every request.

Caching it on the server is a much better solution I believe.

Note: You need using System.Text.Json; for using JsonSerializer

CodePudding user response:

Does this what you want?

public ActionResult Index()
{
    HttpCookie testCookie = new HttpCookie("test");
    testCookie["name"] = "user1";
    testCookie["age"] = "18";
    testCookie.Expires.Add(new TimeSpan(0, 1, 0));
    Response.Cookies.Add(testCookie);
    return View();
}

enter image description here

  • Related