Reputation: 708
How can i use cookies in ASP MVC 6? I want to set and read cookie variables .
HttpCookie class can't be resolved .
Only the following line works but i couldn't find a way to read the cookie after adding it . Response.Cookies.Append("test", "test");
Upvotes: 6
Views: 7046
Reputation: 3619
The answer from Victor Hurdugaci applies to pre-RC2 releases and this was changed a little bit, so here is the current (and hopefully final) stage:
You set the cookie on the Response by:
HttpContext.Response.Cookies.Append("key", "value");
Here cookies is an IResponseCookies
. You can only write to it.
This will be then sent to the browser.
You can read the cookies sent by the browser on the Request object:
HttpContext.Request.Cookies["key"]
Here Cookies is an IRequestCookieCollection
, so you can also read from it.
Upvotes: 7
Reputation: 28425
Take a look at how cookies are used in the official MusicStore sample: https://github.com/aspnet/MusicStore/blob/a7ba4f8ffe5ed23b2a2d55e8e1226e64066a7ada/src/MusicStore/Models/ShoppingCart.cs#L152
public string GetCartId(HttpContext context)
{
var sessionCookie = context.Request.Cookies.Get("Session");
Upvotes: 11