找到你要的答案

Q:How to delete HttpCookie object value in class file

Q:如何删除文件httpcookie类对象的价值

when I assign a cookie like below

string sKey = txtUName.Text + txtPwd.Text;
HttpCookie uidpwd = new HttpCookie("uidpwd");
 uidpwd.Value = sKey;
Response.Cookies.Add(uidpwd);

so want to delete it in class file like below

HttpContext.Current.Request.Cookies["uidpwd"].Expires = DateTime.Now.AddSeconds(1);

but throwing an error

Object reference not set to an instance of an object

当我分配如下的cookie时

string sKey = txtUName.Text + txtPwd.Text;
HttpCookie uidpwd = new HttpCookie("uidpwd");
 uidpwd.Value = sKey;
Response.Cookies.Add(uidpwd);

所以想删除它在类文件如下

HttpContext.Current.Request.Cookies["uidpwd"].Expires = DateTime.Now.AddSeconds(1);

但抛出一个错误

对象引用未设置为对象实例

answer1: 回答1:

Request is collection of incoming stuff, what you're looking for is Response. When browser sends you a cookie, .NET framework translates that to Request.Cookies property; and for application scenario you can think about this collection as read-only collection. When you want to set a cookie; you have to add it to Response.Cookies collection.

So the expiration should look like:

HttpContext.Current.Response.Cookies.Add(
  new HttpCookie("uidpwd") { Expires = DateTime.Now.AddDays(-1) }
);

请求是传入的东西的集合,你正在寻找的是响应。当浏览器向您发送cookie时,.NET框架将其转换为请求属性;而对于应用程序场景,则可以将该集合视为只读集合。当您想要设置cookie时,您必须将其添加到响应。

所以到期应该看起来像:

HttpContext.Current.Response.Cookies.Add(
  new HttpCookie("uidpwd") { Expires = DateTime.Now.AddDays(-1) }
);
c#