我构建了一个ActionFilter来托管我的MVC网站上的页面记录器,并且需要将一些值保存到cookie中。我使用以下代码编写cookie:
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);
});
}
}
Cookie似乎出现在集合中,但在记录后续页面匹配时不可用。
谢谢, 克里斯
答案 0 :(得分:9)
尝试添加新Cookie而不是修改现有集合:
HttpCookie cookie = new HttpCookie("adid", MyValue);
cookie.Expires = DateTime.Now.AddDays(30);
filterContext.HttpContext.Response.Cookies.Add(cookie);
答案 1 :(得分:1)
您是否设置了Cookie过期时间?默认cookie过期是会话cookie(在浏览器关闭时删除)。要将cookie保存到磁盘,必须为其提供未来日期。