Remove or Reset Cookies

被刻印的时光 ゝ 提交于 2020-01-01 11:49:40

问题


I am setting a cookie Request.Cookies("TemplateName").value on one of my pages(page 3) of my application. Now I can navigate from page 3 to page 4 and page 2 and retain the value of the cookie. But now when I logout and login again it still has the value, how can I reset the value of the cookie to be blank "" when I start a new instance?

I tried:

Request.Cookies("TemplateName").Expires = Now
Request.Cookies("TemplateName").value = "" 

On my homepage, but the cookie still retains the value on page 2 and 3.


回答1:


You need to use the Response not the Request

Response.Cookies["TemplateName"].Value = "";

Response.Cookies["TemplateName"].Expires = DateTime.Now;

EDIT For VB.

Dim subkeyName As String
subkeyName = "userName"
Dim aCookie As HttpCookie = Request.Cookies("userInfo")
aCookie.Values.Remove(subkeyName)
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)


Response.Cookies("userName").Value = "patrick"
Response.Cookies("userName").Expires = DateTime.Now.AddDays(1)

These Examples come right off the MSDN site

SideNote

Often people attempt to use

Request.Cookies.Remove("MyCookie");

Which will only remove the cookie from the "request collection", If you want to remove a cookie then you need to expire it. More info here




回答2:


This might sound stupid.

But are you trying to set cookie from any other place? Search for the code for TemplateName, if that helps.




回答3:


I'm not as familiar with .Net but with web apps in general you need to make sure that you set your response headers before writing out any body, otherwise they may not be sent. Just something to double check.



来源:https://stackoverflow.com/questions/387488/remove-or-reset-cookies

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