[英]ASP.NET MVC 5 - Cookies being not created
I am having my controller action that calls a private method that handles a cookie. 我的控制器操作调用了处理cookie的私有方法。 The problem is that the cookie is not being created at all.
问题在于根本没有创建cookie。 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.
我在SO上阅读了多篇文章,但没有找到答案,因为我认为此代码中的Cookie处理是正确的。
Is there any web.config setting that I need to check in regards to cookies? 关于cookie,我需要检查任何web.config设置吗? 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. 我调试了代码,可以看到代码中实际上设置了cookie,但是一旦加载页面并查看cookie,cookie就不存在了。
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;
}
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. Cookies开始工作,现在正在创建。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.