Cookies in ASP vnext

巧了我就是萌 提交于 2020-01-23 06:35:46

问题


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");


回答1:


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"); 



回答2:


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.



来源:https://stackoverflow.com/questions/29064785/cookies-in-asp-vnext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!