title: .NET MVC Write Cookie from ActionFilter
body: <p>I built an ActionFilter to host a page hit logger on my MVC site and have the need to save some values into cookie. I've used the following code to write the cookie:</p>
  
  <pre><code>public class LogRequestAttribute : ActionFilterAttribute, IActionFilter
  {
     void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
     {
         if(filterContext.HttpContext.Request.UserHostAddress != "127.0.0.1")
             ThreadPool.QueueUserWorkItem(delegate
             {
                 string adid = filterContext.HttpContext.Request.QueryString["adid"] != null 
                     ? (string)filterContext.HttpContext.Request.QueryString["adid"] : string.Empty;
  
                 if (!String.IsNullOrEmpty(adid))
                 {
                     HttpCookie cookie = new HttpCookie("adid", adid);
                     cookie.Expires = DateTime.Now.AddDays(30);
                     filterContext.HttpContext.Response.Cookies.Add(cookie);
                 }
  
                 DomainModel.Concrete.SqlPageHitActivity logger 
                     = new DomainModel.Concrete.SqlPageHitActivity(
                         System.Configuration.ConfigurationManager.ConnectionStrings["TrackingConnectionString"].ConnectionString);
  
                 DomainModel.Entities.PageHitActivity hit = new DomainModel.Entities.PageHitActivity
                 {
                     AdIdentifier = filterContext.HttpContext.Response.Cookies["adid"].Value == null ? string.Empty : filterContext.HttpContext.Response.Cookies["adid"].Value,
                     Authenticated = filterContext.HttpContext.Request.IsAuthenticated,
                     Browser = filterContext.HttpContext.Request.UserAgent,
                     CookieId = string.Empty,
                     Parameters = string.Empty,
                     Referer = filterContext.HttpContext.Request.UrlReferrer == null ? string.Empty : filterContext.HttpContext.Request.UrlReferrer.ToString(),
                     RequestDate = DateTime.Now,
                     RequestorIP = filterContext.HttpContext.Request.UserHostAddress,
                     SessionId = string.Empty,
                     SiteId = 1,
                     Target = filterContext.HttpContext.Request.Url != null ? filterContext.HttpContext.Request.Url.AbsoluteUri : string.Empty,
                     UserId = filterContext.HttpContext.Request.IsAuthenticated ? filterContext.HttpContext.User.Identity.Name : string.Empty
                 };
                 logger.LogHit(hit);
             });
     }
  }
  </code></pre>
  
  <p>The cookie seems to appear in the collection but is not available when a subsequent page hit is logged.</p>
  
  <p>Thanks,
  Chris </p>