C# 如何从 .Net 中删除 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12116511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete cookie from .Net
提问by cagin
Possible Duplicate:
Delete cookie on clicking sign out
可能重复:
点击退出时删除 cookie
I want to delete cookies when the user logout.
我想在用户注销时删除 cookie。
Here is my code:
这是我的代码:
if (HttpContext.Current.Request.Cookies["currentUser"] != null)
{
DeleteCookie(HttpContext.Current.Request.Cookies["currentUser"]);
}
public void DeleteCookie(HttpCookie httpCookie)
{
try
{
httpCookie.Value = null;
httpCookie.Expires = DateTime.Now.AddMinutes(-20);
HttpContext.Current.Request.Cookies.Add(httpCookie);
}
catch (Exception ex)
{
throw (ex);
}
}
But it doesn't work. Do you have any suggestion?
但它不起作用。你有什么建议吗?
采纳答案by cagin
HttpCookie currentUserCookie = HttpContext.Current.Request.Cookies["currentUser"];
HttpContext.Current.Response.Cookies.Remove("currentUser");
currentUserCookie.Expires = DateTime.Now.AddDays(-10);
currentUserCookie.Value = null;
HttpContext.Current.Response.SetCookie(currentUserCookie);
It works.
有用。
回答by medkg15
Add the cookie (with past expiration) to the HttpContext.Current.Response.Cookies collection instead. Request is for reading the cookies the server was sent - response is for sending cookies back to the client.
将 cookie(已过期)添加到 HttpContext.Current.Response.Cookies 集合。请求用于读取服务器发送的 cookie - 响应用于将 cookie 发送回客户端。
回答by Tim Schmelter
Instead of adding the cookie, you should change the Response'scookies Expiresto a value in the past:
您应该将Response'scookie更改Expires为过去的值,而不是添加 cookie :
if (Request.Cookies["currentUser"] != null)
{
Response.Cookies["currentUser"].Expires = DateTime.Now.AddDays(-1);
}
Sidenote: Instead of throw exyou should just throwit to keep its stacktrace. C#: Throwing Custom Exception Best Practices
旁注:而不是throw ex你应该只throw保留它的堆栈跟踪。C#:抛出自定义异常最佳实践
回答by S..
Maybe you can make use of Response.Cookies.Clear() or Response.Cookies.Remove().
也许您可以使用 Response.Cookies.Clear() 或 Response.Cookies.Remove()。

