I have a cookie that I add to the response, but if a cookie with the same key already exists I want to remove it otherwise I end up with 2 cookies of the same key.
I thought by simply expiring the cookie it would remove it from the browser?
HttpCookie cookie = new HttpCookie("UserCookie");
cookie.Value = encTicket;
if (HttpContext.Current.Request.Cookies["UserCookie"] != null)
ClearCookie("UserCookie");
HttpContext.Current.Response.Cookies.Add(cookie);
private static void ClearCookie(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
var _response = httpContext.Response;
HttpCookie cookie = new HttpCookie(key)
{
Expires = DateTime.Now.AddMonths(-1),
Value = null
};
_response.Cookies.Add(cookie);
}
Any help much appreciated.
For now I'm just selecting the last cookie value in the collection, although I realise this is a massive hack. Any better suggestions very welcome.
string value = "";
for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
{
if (HttpContext.Current.Request.Cookies[i].Name == "UserCookie")
value = HttpContext.Current.Request.Cookies[i].Value;
}