Reputation: 6772
I am having my controller action that calls a private method that handles a cookie. The problem is that the cookie is not being created at all. I read multiple posts on SO but I haven't found an answer as I think that my handling cookies in this code is correct.
Is there any web.config setting that I need to check in regards to cookies? I also tried different browsers.
I debugged the code and I can see that the cookie is actually set in the code but as soon as I load the page and have a look at cookies the cookie is not there.
private ABHomeModel HandleWhiteBoxCookie(ABHomeModel model)
{
var whiteBox = _whiteBoxService.GetActiveWhiteBox();
if (model.WhiteBox != null)
{
const string cookieName = "whiteBox";
var whiteBoxCookie = HttpContext.Request.Cookies.Get(cookieName);
if (whiteBoxCookie != null)
{
var displayedTimes = Convert.ToInt32(whiteBoxCookie.Value);
if (displayedTimes < 2)
{
displayedTimes++;
var cookie = new HttpCookie(cookieName, displayedTimes.ToString())
{
Expires = new DateTime().AddMonths(1),
Secure = false
};
HttpContext.Response.Cookies.Set(cookie);
ViewBag.IsWhiteBoxActive = true;
}
else
{
ViewBag.IsWhiteBoxActive = false;
}
}
else
{
var cookie = new HttpCookie(cookieName, "1")
{
HttpOnly = true,
Domain = Request.Url.Host,
Expires = DateTime.Now.AddMonths(1),
Secure = false
};
HttpContext.Response.Cookies.Add(cookie);
ViewBag.IsWhiteBoxActive = true;
}
model.WhiteBox = whiteBox;
}
return model;
}
Upvotes: 0
Views: 3542
Reputation: 6772
My colleague found the issue. It is in regard to setting the domain. As soon as we removed this line:
Domain = Request.Url.Host,
The cookies started working and are now being created.
The full updated code of the method:
private ABHomeModel HandleWhiteBoxCookie(ABHomeModel model)
{
var whiteBox = _whiteBoxService.GetActiveWhiteBox();
if (whiteBox != null)
{
const string cookieName = "whiteBox";
var whiteBoxCookie = HttpContext.Request.Cookies.Get(cookieName);
if (whiteBoxCookie != null)
{
var displayedTimes = Convert.ToInt32(whiteBoxCookie.Value);
if (displayedTimes < 2)
{
displayedTimes++;
var cookie = new HttpCookie(cookieName, displayedTimes.ToString())
{
HttpOnly = true,
Secure = false
};
HttpContext.Response.Cookies.Set(cookie);
ViewBag.IsWhiteBoxActive = true;
}
else
{
ViewBag.IsWhiteBoxActive = false;
}
}
else
{
var cookie = new HttpCookie(cookieName, "1")
{
HttpOnly = true,
Expires = DateTime.Now.AddMonths(1),
Secure = false
};
HttpContext.Response.Cookies.Add(cookie);
ViewBag.IsWhiteBoxActive = true;
}
model.WhiteBox = whiteBox;
}
return model;
}
Upvotes: 1