If a request comes in with a certain cookie set, I want to delete that cookie, and redirect back to the same action (and preserve querystring, route values, etc.)
I expect that in the second (redirected) request, the cookie will be gone. But it isn't.
My action method:
[DeleteCookie]
public virtual ActionResult doStuff() {
// blah
}
My action filter:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class DeleteCookieAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext context) {
var request = context.HttpContext.Request;
if (request.Cookies.AllKeys.Contains("foo")) {
request.Cookies["foo"].Expires = DateTime.Now.AddYears(-1); // I tried this
request.Cookies.Remove("foo"); // I tried this
context.Result = new RedirectToRouteResult(context.RouteData.Values);
}
base.OnActionExecuting(_filterContext);
}
}
During the first request, once I delete the cookie, it disappears from the request. But in the second redirected request, it's still there! And so the code above goes into an infinite loop.
How do I remove it?
Try this:
HttpCookie cookie = Request.Cookies["foo"];
if (cookie != null)
{
cookie .Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie);
}