如何通过 C# 代码删除外部站点 Cookie
本文关键字:外部 站点 Cookie 码删除 代码 何通过 | 更新日期: 2023-09-27 18:31:23
我有一个用于Windows Azure身份验证的身份验证页面,其中身份验证在 https://login.microsoftonline.com/login.srf?wa=wsignin1.0&wtrealm=.......上执行。身份验证成功后,我们将重定向到我们的网站。
我们需要删除在此 URL 上生成的 cookie 才能注销。 任何人都可以为我提供代码,通过该代码我们可以删除外部站点 cookie。
我们尝试使用以下代码删除,但无法成功。
public void deleteallcookies()
{
int limit = Request.Cookies.Count;
HttpCookie aCookie; //Instantiate a cookie placeholder
string cookieName;
//Loop through the cookies
for(int i = 0; i < limit; i++)
{
cookieName = Request.Cookies[i].Name; //get the name of the current cookie
aCookie = new HttpCookie(cookieName);
aCookie.Value = ""; //set a blank value to the cookie
aCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(aCookie); //Set the cookie
}
}
您希望从响应而不是请求中获取cookie,即
cookieName = Response.Cookies[i].Name;
您还可以更优雅地枚举,如下所示:
string[] myCookies = HttpContext.Current.Request.Cookies.AllKeys;
foreach (string cookieName in myCookies)
{
var cookie = HttpContext.Current.Response.Cookies[cookieName];
if (cookie != null)
{
cookie.Value = "";
cookie.Expires = DateTime.Now.AddDays(-1);
}
}