Cookie не удаляется
Я использую следующий код для установки cookie в моем приложении asp.net mvc (С#):
public static void SetValue(string key, string value, DateTime expires)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
HttpCookie cookie = new HttpCookie(key, value) { Expires = expires };
_response.Cookies.Set(cookie);
}
Мне нужно удалить файлы cookie, когда пользователь нажимает кнопку выхода из системы. Набор cookie не удаляется/удаляется с помощью Clear/Remove. Код выглядит следующим образом:
public static void Clear()
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
_request.Cookies.Clear();
_response.Cookies.Clear();
}
public static void Remove(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
if (_request.Cookies[key] != null)
{
_request.Cookies.Remove(key);
}
if (_response.Cookies[key] != null)
{
_response.Cookies.Remove(key);
}
}
Я пробовал обе вышеперечисленные функции, но файл cookie существует, когда я пытаюсь проверить существование.
public static bool Exists(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
return _request.Cookies[key] != null;
}
Что может быть проблемой здесь? или что мне нужно сделать, чтобы удалить/удалить файл cookie?
Ответы
Ответ 1
Очистка файлов cookie ответа не указывает браузеру очистить файл cookie, он просто не отправляет файл cookie обратно в браузер. Чтобы указать браузеру очистить файл cookie, вам нужно сказать, что файл cookie истек, например.
public static void Clear(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_response = httpContext.Response;
HttpCookie cookie = new HttpCookie(key)
{
Expires = DateTime.Now.AddDays(-1) // or any other time in the past
};
_response.Cookies.Set(cookie);
}
Ответ 2
Коллекция Cookies в объектах Request and Response не является прокси-серверами для файлов cookie в браузере, они представляют собой набор файлов cookie, которые браузер отправляет вам, и вы отправляете обратно. Если вы удалите файл cookie из запроса, это полностью серверная сторона, и если в ответе нет файлов cookie, вы просто не собираетесь отправлять какие-либо вещи клиенту, что не изменит набор файлов cookie в браузере на все.
Чтобы удалить файл cookie, убедитесь, что он в коллекции cookie ответов, но имеет время истечения в прошлом.
Ответ 3
Просто чтобы добавить что-то еще, я также передаю значение обратно как null, например.
public static void RemoveCookie(string cookieName)
{
if (HttpContext.Current.Response.Cookies[cookieName] != null)
{
HttpContext.Current.Response.Cookies[cookieName].Value = null;
HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.Now.AddMonths(-1);
}
}
Ответ 4
Лучший способ реализовать это - использовать инструмент, например Reflector, и посмотреть, как метод System.Web.Security.FormsAuthentication.SignOut реализует удаление cookie аутентификации.
В Reflector откройте System.Web и перейдите к объекту FormsAuthentication и найдите метод SignOut. Щелкните правой кнопкой мыши на нем и выберите "Разберите" (выберите язык в меню).
VB.NET
Public Shared Sub SignOut()
FormsAuthentication.Initialize
Dim current As HttpContext = HttpContext.Current
Dim flag As Boolean = current.CookielessHelper.DoesCookieValueExistInOriginal("F"c)
current.CookielessHelper.SetCookieValue("F"c, Nothing)
If (Not CookielessHelperClass.UseCookieless(current, False, FormsAuthentication.CookieMode) OrElse current.Request.Browser.Cookies) Then
Dim str As String = String.Empty
If (current.Request.Browser.Item("supportsEmptyStringInCookieValue") = "false") Then
str = "NoCookie"
End If
Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, str)
cookie.HttpOnly = True
cookie.Path = FormsAuthentication._FormsCookiePath
cookie.Expires = New DateTime(&H7CF, 10, 12)
cookie.Secure = FormsAuthentication._RequireSSL
If (Not FormsAuthentication._CookieDomain Is Nothing) Then
cookie.Domain = FormsAuthentication._CookieDomain
End If
current.Response.Cookies.RemoveCookie(FormsAuthentication.FormsCookieName)
current.Response.Cookies.Add(cookie)
End If
If flag Then
current.Response.Redirect(FormsAuthentication.GetLoginPage(Nothing), False)
End If
End Sub
В приведенном выше примере я смог создать общий метод RemoveCookie() в общей сборке, код ниже:
VB.NET
''' <summary>
''' Method to remove a cookie
''' </summary>
''' <param name="key">Key</param>
''' <remarks></remarks>
Public Shared Sub RemoveCookie(ByVal key As String)
' Encode key for retrieval and remove cookie
With HttpContext.Current
Dim cookie As New HttpCookie(.Server.UrlEncode(key))
If Not IsNothing(cookie) Then
With cookie
.HttpOnly = True
.Expires = New DateTime(&H7CF, 10, 12)
End With
' Remove from server (has no effect on client)
.Response.Cookies.Remove(.Server.UrlEncode(key))
' Add expired cookie to client, effectively removing it
.Response.Cookies.Add(cookie)
End If
End With
End Sub
Протестировав это с помощью FireBug и надстройки Cookie для FireBug (в FireFox), я могу подтвердить, что cookie немедленно удаляется.
Любые вопросы, не стесняйтесь сообщать мне.